标准库
- 1: archive
- 2: compress
- 3: container
- 4: crypto
- 4.1: aes
- 4.2: cipher
- 4.3: crypto
- 4.4: des
- 4.5: dsa
- 4.6: ecdh
- 4.7: ecdsa
- 4.8: ed25519
- 4.9: elliptic
- 4.10: hmac
- 4.11: md5
- 4.12: rand
- 4.13: rc4
- 4.14: rsa
- 4.15: sha1
- 4.16: sha256
- 4.17: sha512
- 4.18: subtle
- 4.19: tls
- 4.20: x509
- 4.21: x509/pkix
- 5: database
- 5.1: sql
- 5.2: sql/driver
- 6: debug
- 7: encoding
- 7.1: ascii85
- 7.2: asn1
- 7.3: base32
- 7.4: base64
- 7.5: binary
- 7.6: csv
- 7.7: encoding
- 7.8: gob
- 7.9: hex
- 7.10: json
- 7.11: pem
- 7.12: xml
- 8: go
- 8.1: ast
- 8.2: build
- 8.3: constant
- 8.4: contraint
- 8.5: doc
- 8.6: doc/comment
- 8.7: format
- 8.8: importer
- 8.9: parser
- 8.10: printer
- 8.11: scanner
- 8.12: token
- 8.13: types
- 9: hash
- 10: html
- 11: image
- 12: index
- 12.1: suffixarray
- 13: internal
- 13.1:
- 13.2:
- 13.3:
- 13.4:
- 13.5:
- 13.6:
- 13.7:
- 13.8:
- 13.9:
- 13.10:
- 13.11:
- 13.12:
- 13.13:
- 13.14:
- 13.15:
- 13.16:
- 13.17:
- 13.18:
- 13.19:
- 13.20:
- 13.21:
- 13.22:
- 13.23:
- 13.24:
- 13.25:
- 13.26:
- 13.27:
- 13.28:
- 13.29:
- 13.30:
- 13.31:
- 13.32:
- 13.33:
- 13.34:
- 13.35:
- 13.36:
- 13.37:
- 13.38:
- 13.39:
- 13.40:
- 13.41:
- 13.42:
- 13.43:
- 13.44:
- 13.45:
- 13.46:
- 13.47:
- 13.48:
- 13.49:
- 13.50:
- 13.51:
- 13.52:
- 13.53:
- 13.54:
- 13.55:
- 13.56:
- 13.57:
- 13.58:
- 13.59:
- 14: io
- 15: log
- 15.1: log
- 15.2: logAnalysis
- 15.3: syslog
- 16: math
- 17: mime
- 17.1: mime
- 17.2: multipart
- 17.3: quotedprintable
- 18: net
- 18.1: fcgi
- 18.2: http
- 18.3: http/cli
- 18.4: http/cookiejar
- 18.5: http/httptest
- 18.6: http/httptrace
- 18.7: http/httputil
- 18.8: mail
- 18.9: net
- 18.10: netip
- 18.11: pprof
- 18.12: rpc
- 18.13: rpc/jsonrpc
- 18.14: smtp
- 18.15: textproto
- 18.16: url
- 19: os
- 20: path
- 21: regexp
- 22: runtime
- 23: sync
- 24: syscall
- 25: testing
- 26: text
- 26.1: scanner
- 26.2: tabwriter
- 26.3: template
- 26.4: template/parse
- 27: time
- 28: bufio
- 29: builtin
- 30: bytes
- 31: context
- 32: embed
- 33: error
- 34: expvar
- 35: flag
- 36: fmt
- 37: plugin
- 38: reflect
- 39: sort
- 40: strconv
- 41: strings
- 42: unicode
- 43: unsafe
1 - archive
1.1 - tar
tar
https://pkg.go.dev/archive/tar@go1.20.1
Package tar implements access to tar archives.
Tape archives (tar) are a file format for storing a sequence of files that can be read and written in a streaming manner. This package aims to cover most variations of the format, including those produced by GNU and BSD tar tools.
Example
|
|
常量
|
|
Type flags for Header.Typeflag.
变量
|
|
函数
This section is empty.
类型
type Format <- go1.10
|
|
Format represents the tar archive format.
The original tar format was introduced in Unix V7. Since then, there have been multiple competing formats attempting to standardize or extend the V7 format to overcome its limitations. The most common formats are the USTAR, PAX, and GNU formats, each with their own advantages and limitations.
The following table captures the capabilities of each format:
| USTAR | PAX | GNU
------------------+--------+-----------+----------
Name | 256B | unlimited | unlimited
Linkname | 100B | unlimited | unlimited
Size | uint33 | unlimited | uint89
Mode | uint21 | uint21 | uint57
Uid/Gid | uint21 | unlimited | uint57
Uname/Gname | 32B | unlimited | 32B
ModTime | uint33 | unlimited | int89
AccessTime | n/a | unlimited | int89
ChangeTime | n/a | unlimited | int89
Devmajor/Devminor | uint21 | uint21 | uint57
------------------+--------+-----------+----------
string encoding | ASCII | UTF-8 | binary
sub-second times | no | yes | no
sparse files | no | yes | yes
The table’s upper portion shows the Header fields, where each format reports the maximum number of bytes allowed for each string field and the integer type used to store each numeric field (where timestamps are stored as the number of seconds since the Unix epoch).
The table’s lower portion shows specialized features of each format, such as supported string encodings, support for sub-second timestamps, or support for sparse files.
The Writer currently provides no support for sparse files.
|
|
Constants to identify various tar formats.
(Format) String <- go1.10
|
|
type Header
|
|
A Header represents a single header in a tar archive. Some fields may not be populated.
For forward compatibility, users that retrieve a Header from Reader.Next, mutate it in some ways, and then pass it back to Writer.WriteHeader should do so by creating a new Header and copying the fields that they are interested in preserving.
func FileInfoHeader <- go1.1
|
|
FileInfoHeader creates a partially-populated Header from fi. If fi describes a symlink, FileInfoHeader records link as the link target. If fi describes a directory, a slash is appended to the name.
Since fs.FileInfo’s Name method only returns the base name of the file it describes, it may be necessary to modify Header.Name to provide the full path name of the file.
(*Header) FileInfo <- go1.1
|
|
FileInfo returns an fs.FileInfo for the Header.
type Reader
|
|
Reader provides sequential access to the contents of a tar archive. Reader.Next advances to the next file in the archive (including the first), and then Reader can be treated as an io.Reader to access the file’s data.
func NewReader
|
|
NewReader creates a new Reader reading from r.
(*Reader) Next
|
|
Next advances to the next entry in the tar archive. The Header.Size determines how many bytes can be read for the next file. Any remaining data in the current file is automatically discarded. At the end of the archive, Next returns the error io.EOF.
If Next encounters a non-local name (as defined by filepath.IsLocal) and the GODEBUG environment variable contains tarinsecurepath=0, Next returns the header with an ErrInsecurePath error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the ErrInsecurePath error and use the returned header.
(*Reader) Read
|
|
Read reads from the current file in the tar archive. It returns (0, io.EOF) when it reaches the end of that file, until Next is called to advance to the next file.
If the current file is sparse, then the regions marked as a hole are read back as NUL-bytes.
Calling Read on special types like TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, and TypeFifo returns (0, io.EOF) regardless of what the Header.Size claims.
type Writer
|
|
Writer provides sequential writing of a tar archive. Write.WriteHeader begins a new file with the provided Header, and then Writer can be treated as an io.Writer to supply that file’s data.
func NewWriter
|
|
NewWriter creates a new Writer writing to w.
(*Writer) Close
|
|
Close closes the tar archive by flushing the padding, and writing the footer. If the current file (from a prior call to WriteHeader) is not fully written, then this returns an error.
(*Writer) Flush
|
|
Flush finishes writing the current file’s block padding. The current file must be fully written before Flush can be called.
This is unnecessary as the next call to WriteHeader or Close will implicitly flush out the file’s padding.
(*Writer) Write
|
|
Write writes to the current file in the tar archive. Write returns the error ErrWriteTooLong if more than Header.Size bytes are written after WriteHeader.
Calling Write on special types like TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, and TypeFifo returns (0, ErrWriteTooLong) regardless of what the Header.Size claims.
(*Writer) WriteHeader
|
|
WriteHeader writes hdr and prepares to accept the file’s contents. The Header.Size determines how many bytes can be written for the next file. If the current file is not fully written, then this returns an error. This implicitly flushes any padding necessary before writing the header.
1.2 - zip
zip
https://pkg.go.dev/archive/zip@go1.20.1
Package zip provides support for reading and writing ZIP archives.
See the ZIP specification for details.
This package does not support disk spanning.
A note about ZIP64:
To be backwards compatible the FileHeader has both 32 and 64 bit Size fields. The 64 bit fields will always contain the correct value and for normal archives both fields will be the same. For files requiring the ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bit fields must be used instead.
常量
|
|
Compression methods.
变量
|
|
函数
func RegisterCompressor <- go1.2
|
|
RegisterCompressor registers custom compressors for a specified method ID. The common methods Store and Deflate are built in.
func RegisterDecompressor <- go1.2
|
|
RegisterDecompressor allows custom decompressors for a specified method ID. The common methods Store and Deflate are built in.
类型
type Compressor <- go1.2
|
|
A Compressor returns a new compressing writer, writing to w. The WriteCloser’s Close method must be used to flush pending data to w. The Compressor itself must be safe to invoke from multiple goroutines simultaneously, but each returned writer will be used only by one goroutine at a time.
type Decompressor <- go1.2
|
|
A Decompressor returns a new decompressing reader, reading from r. The ReadCloser’s Close method must be used to release associated resources. The Decompressor itself must be safe to invoke from multiple goroutines simultaneously, but each returned reader will be used only by one goroutine at a time.
type File
|
|
A File is a single file in a ZIP archive. The file information is in the embedded FileHeader. The file content can be accessed by calling Open.
(*File) DataOffset <- go1.2
|
|
DataOffset returns the offset of the file’s possibly-compressed data, relative to the beginning of the zip file.
Most callers should instead use Open, which transparently decompresses data and verifies checksums.
(*File) Open
|
|
Open returns a ReadCloser that provides access to the File’s contents. Multiple files may be read concurrently.
(*File) OpenRaw <- go1.17
|
|
OpenRaw returns a Reader that provides access to the File’s contents without decompression.
type FileHeader
|
|
FileHeader describes a file within a ZIP file. See the ZIP specification for details.
func FileInfoHeader
|
|
FileInfoHeader creates a partially-populated FileHeader from an fs.FileInfo. Because fs.FileInfo’s Name method returns only the base name of the file it describes, it may be necessary to modify the Name field of the returned header to provide the full path name of the file. If compression is desired, callers should set the FileHeader.Method field; it is unset by default.
(*FileHeader) FileInfo
|
|
FileInfo returns an fs.FileInfo for the FileHeader.
Example
|
|
(*FileHeader) Mode
|
|
Mode returns the permission and mode bits for the FileHeader.
Example
|
|
(*FileHeader) SetMode
|
|
SetMode changes the permission and mode bits for the FileHeader.
type ReadCloser
|
|
A ReadCloser is a Reader that must be closed when no longer needed.
func OpenReader
|
|
OpenReader will open the Zip file specified by name and return a ReadCloser.
(*ReadCloser) Close
|
|
Close closes the Zip file, rendering it unusable for I/O.
type Reader
|
|
A Reader serves content from a ZIP archive.
Example
|
|
func NewReader
|
|
NewReader returns a new Reader reading from r, which is assumed to have the given size in bytes.
If any file inside the archive uses a non-local name (as defined by filepath.IsLocal) or a name containing backslashes and the GODEBUG environment variable contains zipinsecurepath=0, NewReader returns the reader with an ErrInsecurePath error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the ErrInsecurePath error and use the returned reader.
(*Reader) Open <- go1.16
|
|
Open opens the named file in the ZIP archive, using the semantics of fs.FS.Open: paths are always slash separated, with no leading / or ../ elements.
(*Reader) RegisterDecompressor <- go1.6
|
|
RegisterDecompressor registers or overrides a custom decompressor for a specific method ID. If a decompressor for a given method is not found, Reader will default to looking up the decompressor at the package level.
type Writer
|
|
Writer implements a zip file writer.
Example
|
|
func NewWriter
|
|
NewWriter returns a new Writer writing a zip file to w.
(*Writer) Close
|
|
Close finishes writing the zip file by writing the central directory. It does not close the underlying writer.
(*Writer) Copy <- go1.17
|
|
Copy copies the file f (obtained from a Reader) into w. It copies the raw form directly bypassing decompression, compression, and validation.
(*Writer) Create
|
|
Create adds a file to the zip file using the provided name. It returns a Writer to which the file contents should be written. The file contents will be compressed using the Deflate method. The name must be a relative path: it must not start with a drive letter (e.g. C:) or leading slash, and only forward slashes are allowed. To create a directory instead of a file, add a trailing slash to the name. The file’s contents must be written to the io.Writer before the next call to Create, CreateHeader, or Close.
(*Writer) CreateHeader
|
|
CreateHeader adds a file to the zip archive using the provided FileHeader for the file metadata. Writer takes ownership of fh and may mutate its fields. The caller must not modify fh after calling CreateHeader.
This returns a Writer to which the file contents should be written. The file’s contents must be written to the io.Writer before the next call to Create, CreateHeader, CreateRaw, or Close.
(*Writer) CreateRaw <- go1.17
|
|
CreateRaw adds a file to the zip archive using the provided FileHeader and returns a Writer to which the file contents should be written. The file’s contents must be written to the io.Writer before the next call to Create, CreateHeader, CreateRaw, or Close.
In contrast to CreateHeader, the bytes passed to Writer are not compressed.
(*Writer) Flush <- go1.4
|
|
Flush flushes any buffered data to the underlying writer. Calling Flush is not normally necessary; calling Close is sufficient.
(*Writer) RegisterCompressor <- go1.6
|
|
RegisterCompressor registers or overrides a custom compressor for a specific method ID. If a compressor for a given method is not found, Writer will default to looking up the compressor at the package level.
Example
|
|
(*Writer) SetComment <- go1.10
|
|
SetComment sets the end-of-central-directory comment field. It can only be called before Close.
(*Writer) SetOffset <- go1.5
|
|
SetOffset sets the offset of the beginning of the zip data within the underlying writer. It should be used when the zip data is appended to an existing file, such as a binary executable. It must be called before any data is written.
2 - compress
2.1 - bzip2
bzip2
https://pkg.go.dev/compress/bzip2@go1.20.1
Package bzip2 implements bzip2 decompression.
常量
This section is empty.
变量
This section is empty.
函数
func NewReader
|
|
NewReader returns an io.Reader which decompresses bzip2 data from r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r.
类型
type StructuralError
|
|
A StructuralError is returned when the bzip2 data is found to be syntactically invalid.
(StructuralError) Error
|
|
2.2 - flate
flate
https://pkg.go.dev/compress/flate@go1.20.1
Package flate implements the DEFLATE compressed data format, described in RFC 1951. The gzip and zlib packages implement access to DEFLATE-based file formats.
Example
|
|
Example
|
|
Example
|
|
常量
|
|
变量
This section is empty.
函数
func NewReader
|
|
NewReader returns a new ReadCloser that can be used to read the uncompressed version of r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r. The reader returns io.EOF after the final block in the DEFLATE stream has been encountered. Any trailing data after the final block is ignored.
The ReadCloser returned by NewReader also implements Resetter.
func NewReaderDict
|
|
NewReaderDict is like NewReader but initializes the reader with a preset dictionary. The returned Reader behaves as if the uncompressed data stream started with the given dictionary, which has already been read. NewReaderDict is typically used to read data compressed by NewWriterDict.
The ReadCloser returned by NewReader also implements Resetter.
类型
type CorruptInputError
|
|
A CorruptInputError reports the presence of corrupt input at a given offset.
(CorruptInputError) Error
|
|
type InternalError
|
|
An InternalError reports an error in the flate code itself.
(InternalError) Error
|
|
Example
|
|
type Reader
|
|
The actual read interface needed by NewReader. If the passed in io.Reader does not also have ReadByte, the NewReader will introduce its own buffering.
type Resetter <- go1.4
|
|
Resetter resets a ReadCloser returned by NewReader or NewReaderDict to switch to a new underlying Reader. This permits reusing a ReadCloser instead of allocating a new one.
Example
|
|
type Writer
|
|
A Writer takes data written to it and writes the compressed form of that data to an underlying writer (see NewWriter).
func NewWriter
|
|
NewWriter returns a new Writer compressing data at the given level. Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression); higher levels typically run slower but compress more. Level 0 (NoCompression) does not attempt any compression; it only adds the necessary DEFLATE framing. Level -1 (DefaultCompression) uses the default compression level. Level -2 (HuffmanOnly) will use Huffman compression only, giving a very fast compression for all types of input, but sacrificing considerable compression efficiency.
If level is in the range [-2, 9] then the error returned will be nil. Otherwise the error returned will be non-nil.
func NewWriterDict
|
|
NewWriterDict is like NewWriter but initializes the new Writer with a preset dictionary. The returned Writer behaves as if the dictionary had been written to it without producing any compressed output. The compressed data written to w can only be decompressed by a Reader initialized with the same dictionary.
(*Writer) Close
|
|
Close flushes and closes the writer.
(*Writer) Flush
|
|
Flush flushes any pending data to the underlying writer. It is useful mainly in compressed network protocols, to ensure that a remote reader has enough data to reconstruct a packet. Flush does not return until the data has been written. Calling Flush when there is no pending data still causes the Writer to emit a sync marker of at least 4 bytes. If the underlying writer returns an error, Flush returns that error.
In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.
(*Writer) Reset <- go1.2
|
|
Reset discards the writer’s state and makes it equivalent to the result of NewWriter or NewWriterDict called with dst and w’s level and dictionary.
(*Writer) Write
|
|
Write writes data to w, which will eventually write the compressed form of data to its underlying writer.
2.3 - gzip
gzip
https://pkg.go.dev/compress/gzip@go1.20.1
Package gzip implements reading and writing of gzip format compressed files, as specified in RFC 1952.
Example
|
|
Example
|
|
常量
|
|
These constants are copied from the flate package, so that code that imports “compress/gzip” does not also have to import “compress/flate”.
变量
|
|
函数
This section is empty.
类型
type Header
|
|
The gzip file stores a header giving metadata about the compressed file. That header is exposed as the fields of the Writer and Reader structs.
Strings must be UTF-8 encoded and may only contain Unicode code points U+0001 through U+00FF, due to limitations of the GZIP file format.
type Reader
|
|
A Reader is an io.Reader that can be read to retrieve uncompressed data from a gzip-format compressed file.
In general, a gzip file can be a concatenation of gzip files, each with its own header. Reads from the Reader return the concatenation of the uncompressed data of each. Only the first header is recorded in the Reader fields.
Gzip files store a length and checksum of the uncompressed data. The Reader will return an ErrChecksum when Read reaches the end of the uncompressed data if it does not have the expected length or checksum. Clients should treat data returned by Read as tentative until they receive the io.EOF marking the end of the data.
func NewReader
|
|
NewReader creates a new Reader reading the given reader. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r.
It is the caller’s responsibility to call Close on the Reader when done.
The Reader.Header fields will be valid in the Reader returned.
(*Reader) Close
|
|
Close closes the Reader. It does not close the underlying io.Reader. In order for the GZIP checksum to be verified, the reader must be fully consumed until the io.EOF.
(*Reader) Multistream <- go1.4
|
|
Multistream controls whether the reader supports multistream files.
If enabled (the default), the Reader expects the input to be a sequence of individually gzipped data streams, each with its own header and trailer, ending at EOF. The effect is that the concatenation of a sequence of gzipped files is treated as equivalent to the gzip of the concatenation of the sequence. This is standard behavior for gzip readers.
Calling Multistream(false) disables this behavior; disabling the behavior can be useful when reading file formats that distinguish individual gzip data streams or mix gzip data streams with other data streams. In this mode, when the Reader reaches the end of the data stream, Read returns io.EOF. The underlying reader must implement io.ByteReader in order to be left positioned just after the gzip stream. To start the next stream, call z.Reset(r) followed by z.Multistream(false). If there is no next stream, z.Reset(r) will return io.EOF.
Example
|
|
(*Reader) Read
|
|
Read implements io.Reader, reading uncompressed bytes from its underlying Reader.
(*Reader) Reset <- go1.3
|
|
Reset discards the Reader z’s state and makes it equivalent to the result of its original state from NewReader, but reading from r instead. This permits reusing a Reader rather than allocating a new one.
type Writer
|
|
A Writer is an io.WriteCloser. Writes to a Writer are compressed and written to w.
func NewWriter
|
|
NewWriter returns a new Writer. Writes to the returned writer are compressed and written to w.
It is the caller’s responsibility to call Close on the Writer when done. Writes may be buffered and not flushed until Close.
Callers that wish to set the fields in Writer.Header must do so before the first call to Write, Flush, or Close.
func NewWriterLevel
|
|
NewWriterLevel is like NewWriter but specifies the compression level instead of assuming DefaultCompression.
The compression level can be DefaultCompression, NoCompression, HuffmanOnly or any integer value between BestSpeed and BestCompression inclusive. The error returned will be nil if the level is valid.
(*Writer) Close
|
|
Close closes the Writer by flushing any unwritten data to the underlying io.Writer and writing the GZIP footer. It does not close the underlying io.Writer.
(*Writer) Flush <- go1.1
|
|
Flush flushes any pending compressed data to the underlying writer.
It is useful mainly in compressed network protocols, to ensure that a remote reader has enough data to reconstruct a packet. Flush does not return until the data has been written. If the underlying writer returns an error, Flush returns that error.
In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.
(*Writer) Reset <- go1.2
|
|
Reset discards the Writer z’s state and makes it equivalent to the result of its original state from NewWriter or NewWriterLevel, but writing to w instead. This permits reusing a Writer rather than allocating a new one.
(*Writer) Write
|
|
Write writes a compressed form of p to the underlying io.Writer. The compressed bytes are not necessarily flushed until the Writer is closed.
2.4 - lzw
lzw
https://pkg.go.dev/compress/lzw@go1.20.1
Package lzw implements the Lempel-Ziv-Welch compressed data format, described in T. A. Welch, “A Technique for High-Performance Data Compression”, Computer, 17(6) (June 1984), pp 8-19.
In particular, it implements LZW as used by the GIF and PDF file formats, which means variable-width codes up to 12 bits and the first two non-literal codes are a clear code and an EOF code.
The TIFF file format uses a similar but incompatible version of the LZW algorithm. See the golang.org/x/image/tiff/lzw package for an implementation.
常量
This section is empty.
变量
This section is empty.
函数
func NewReader
|
|
NewReader creates a new io.ReadCloser. Reads from the returned io.ReadCloser read and decompress data from r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r. It is the caller’s responsibility to call Close on the ReadCloser when finished reading. The number of bits to use for literal codes, litWidth, must be in the range [2,8] and is typically 8. It must equal the litWidth used during compression.
It is guaranteed that the underlying type of the returned io.ReadCloser is a *Reader.
func NewWriter
|
|
NewWriter creates a new io.WriteCloser. Writes to the returned io.WriteCloser are compressed and written to w. It is the caller’s responsibility to call Close on the WriteCloser when finished writing. The number of bits to use for literal codes, litWidth, must be in the range [2,8] and is typically 8. Input bytes must be less than 1«litWidth.
It is guaranteed that the underlying type of the returned io.WriteCloser is a *Writer.
类型
type Order
|
|
Order specifies the bit ordering in an LZW data stream.
|
|
type Reader <- go1.17
|
|
Reader is an io.Reader which can be used to read compressed data in the LZW format.
(*Reader) Close <- go1.17
|
|
Close closes the Reader and returns an error for any future read operation. It does not close the underlying io.Reader.
(*Reader) Read <- go1.17
|
|
Read implements io.Reader, reading uncompressed bytes from its underlying Reader.
(*Reader) Reset <- go1.17
|
|
Reset clears the Reader’s state and allows it to be reused again as a new Reader.
type Writer <- go1.17
|
|
Writer is an LZW compressor. It writes the compressed form of the data to an underlying writer (see NewWriter).
(*Writer) Close <- go1.17
|
|
Close closes the Writer, flushing any pending output. It does not close w’s underlying writer.
(*Writer) Reset <- go1.17
|
|
Reset clears the Writer’s state and allows it to be reused again as a new Writer.
(*Writer) Write <- go1.17
|
|
Write writes a compressed representation of p to w’s underlying writer.
2.5 - zlib
zlib
https://pkg.go.dev/compress/zlib@go1.20.1
Package zlib implements reading and writing of zlib format compressed data, as specified in RFC 1950.
The implementation provides filters that uncompress during reading and compress during writing. For example, to write compressed data to a buffer:
|
|
and to read that data back:
r, err := zlib.NewReader(&b)
io.Copy(os.Stdout, r)
r.Close()
常量
|
|
These constants are copied from the flate package, so that code that imports “compress/zlib” does not also have to import “compress/flate”.
变量
|
|
函数
func NewReader
|
|
NewReader creates a new ReadCloser. Reads from the returned ReadCloser read and decompress data from r. If r does not implement io.ByteReader, the decompressor may read more data than necessary from r. It is the caller’s responsibility to call Close on the ReadCloser when done.
The ReadCloser returned by NewReader also implements Resetter.
Example
|
|
func NewReaderDict
|
|
NewReaderDict is like NewReader but uses a preset dictionary. NewReaderDict ignores the dictionary if the compressed data does not refer to it. If the compressed data refers to a different dictionary, NewReaderDict returns ErrDictionary.
The ReadCloser returned by NewReaderDict also implements Resetter.
类型
type Resetter <- go1.4
|
|
Resetter resets a ReadCloser returned by NewReader or NewReaderDict to switch to a new underlying Reader. This permits reusing a ReadCloser instead of allocating a new one.
type Writer
|
|
A Writer takes data written to it and writes the compressed form of that data to an underlying writer (see NewWriter).
func NewWriter
|
|
NewWriter creates a new Writer. Writes to the returned Writer are compressed and written to w.
It is the caller’s responsibility to call Close on the Writer when done. Writes may be buffered and not flushed until Close.
Example
|
|
func NewWriterLevel
|
|
NewWriterLevel is like NewWriter but specifies the compression level instead of assuming DefaultCompression.
The compression level can be DefaultCompression, NoCompression, HuffmanOnly or any integer value between BestSpeed and BestCompression inclusive. The error returned will be nil if the level is valid.
func NewWriterLevelDict
|
|
NewWriterLevelDict is like NewWriterLevel but specifies a dictionary to compress with.
The dictionary may be nil. If not, its contents should not be modified until the Writer is closed.
(*Writer) Close
|
|
Close closes the Writer, flushing any unwritten data to the underlying io.Writer, but does not close the underlying io.Writer.
(*Writer) Flush
|
|
Flush flushes the Writer to its underlying io.Writer.
(*Writer) Reset <- go1.2
|
|
Reset clears the state of the Writer z such that it is equivalent to its initial state from NewWriterLevel or NewWriterLevelDict, but instead writing to w.
(*Writer) Write
|
|
Write writes a compressed form of p to the underlying io.Writer. The compressed bytes are not necessarily flushed until the Writer is closed or explicitly flushed.
3 - container
3.1 - heap
heap
https://pkg.go.dev/container/heap@go1.20.1
Package heap provides heap operations for any type that implements heap.Interface. A heap is a tree with the property that each node is the minimum-valued node in its subtree.
包heap为任何实现heap.Interface的类型提供堆操作。堆是一棵树,其属性是每个节点都是其子树中的最小值节点。
The minimum element in the tree is the root, at index 0.
树中的最小元素是根,索引为0。
A heap is a common way to implement a priority queue. To build a priority queue, implement the Heap interface with the (negative) priority as the ordering for the Less method, so Push adds items while Pop removes the highest-priority item from the queue. The Examples include such an implementation; the file example_pq_test.go has the complete source.
heap 是实现优先级队列的一种常见方式。要建立一个优先级队列,要用(负)优先级作为Less方法的排序来实现Heap接口,因此Push增加项目,而Pop从队列中删除优先级最高的项目。实例中包括这样的实现;文件example_pq_test.go中有完整的源代码。
Example
|
|
Example
|
|
常量
This section is empty.
变量
This section is empty.
函数
func Fix <- go1.2
|
|
Fix re-establishes the heap ordering after the element at index i has changed its value. Changing the value of the element at index i and then calling Fix is equivalent to, but less expensive than, calling Remove(h, i) followed by a Push of the new value. The complexity is O(log n) where n = h.Len().
Fix在索引i处的元素改变其值后重新建立堆的顺序。改变索引i处元素的值,然后调用Fix,相当于调用Remove(h, i),然后推送新的值,但成本较低。复杂度是O(log n),其中n = h.Len()。
func Init
|
|
Init establishes the heap invariants required by the other routines in this package. Init is idempotent with respect to the heap invariants and may be called whenever the heap invariants may have been invalidated. The complexity is O(n) where n = h.Len().
Init建立了本包中其他例程所要求的堆不变性。Init对于堆不变性来说是等价的,只要堆不变性可能已经失效,就可以调用它。复杂度为O(n),其中n = h.Len()。
func Pop
|
|
Pop removes and returns the minimum element (according to Less) from the heap. The complexity is O(log n) where n = h.Len(). Pop is equivalent to Remove(h, 0).
Pop删除并返回堆中的最小元素(根据Less)。复杂度为O(log n),其中n = h.Len()。Pop等同于Remove(h, 0)。
func Push
|
|
Push pushes the element x onto the heap. The complexity is O(log n) where n = h.Len().
Push将元素x推到堆上。复杂度为O(log n),其中n = h.Len()。
func Remove
|
|
Remove removes and returns the element at index i from the heap. The complexity is O(log n) where n = h.Len().
Remove从堆中删除并返回索引为i的元素。复杂度为O(log n),其中n = h.Len()。
类型
type Interface
|
|
The Interface type describes the requirements for a type using the routines in this package. Any type that implements it may be used as a min-heap with the following invariants (established after Init has been called or if the data is empty or sorted):
接口类型描述了一个使用本包中的例程的类型的要求。任何实现它的类型都可以作为最小堆使用,并具有以下不变性(在调用Init后或数据为空或被排序后建立):
!h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()
Note that Push and Pop in this interface are for package heap’s implementation to call. To add and remove things from the heap, use heap.Push and heap.Pop.
注意,这个接口中的Push和Pop是供包堆的实现调用的。要从堆中添加和删除东西,请使用heap.Push和heap.Pop。
3.2 - list
list
https://pkg.go.dev/container/list@go1.20.1
Package list implements a doubly linked list.
包list实现了一个双链表。
To iterate over a list (where l is a *List):
要在一个列表上进行迭代(其中l是一个*List):
for e := l.Front(); e != nil; e = e.Next() {
// do something with e.Value
//对e.Value做一些处理
}
Example
|
|
常量
This section is empty.
变量
This section is empty.
函数
This section is empty.
类型
type Element
|
|
Element is an element of a linked list.
Element是链接列表的一个元素。
(*Element) Next
|
|
Next returns the next list element or nil.
Next 返回下一个列表元素或nil。
(*Element) Prev
|
|
Prev returns the previous list element or nil.
Prev返回前一个列表元素或nil。
type List
|
|
List represents a doubly linked list. The zero value for List is an empty list ready to use.
List表示一个双链表。List的零值是一个准备使用的空列表。
func New
|
|
New returns an initialized list.
New返回一个初始化的列表。
(*List) Back
|
|
Back returns the last element of list l or nil if the list is empty.
Back返回列表l的最后一个元素,如果列表为空,则返回nil。
(*List) Front
|
|
Front returns the first element of list l or nil if the list is empty.
Front返回列表l的第一个元素,如果列表为空则返回nil。
(*List) Init
|
|
Init initializes or clears list l.
Init 初始化或清除列表l。
(*List) InsertAfter
|
|
InsertAfter inserts a new element e with value v immediately after mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.
InsertAfter在mark之后插入一个新的元素e,其值为v,并返回e。如果mark不是l的一个元素,列表不会被修改。mark不能是nil。
(*List) InsertBefore
|
|
InsertBefore inserts a new element e with value v immediately before mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.
InsertBefore在mark之前插入一个新的元素e,其值为v,并返回e,如果mark不是l的一个元素,列表就不会被修改。mark不能是nil。
(*List) Len
|
|
Len returns the number of elements of list l. The complexity is O(1).
Len返回列表l的元素数,其复杂度为O(1)。
(*List) MoveAfter <- go1.2
|
|
MoveAfter moves element e to its new position after mark. If e or mark is not an element of l, or e == mark, the list is not modified. The element and mark must not be nil.
MoveAfter将元素e移动到mark之后的新位置。如果e或mark不是l的一个元素,或者e == mark,列表不会被修改。元素和mark不能是nil。
(*List) MoveBefore <- go1.2
|
|
MoveBefore moves element e to its new position before mark. If e or mark is not an element of l, or e == mark, the list is not modified. The element and mark must not be nil.
MoveBefore将元素e移动到mark之前的新位置。如果e或mark不是l的一个元素,或者e == mark,列表不会被修改。元素和mark不能是nil。
(*List) MoveToBack
|
|
MoveToBack moves element e to the back of list l. If e is not an element of l, the list is not modified. The element must not be nil.
MoveToBack把元素e移到列表l的后面。如果e不是l的一个元素,列表不会被修改。该元素不能是nil。
(*List) MoveToFront
|
|
MoveToFront moves element e to the front of list l. If e is not an element of l, the list is not modified. The element must not be nil.
MoveToFront把元素e移到列表l的前面,如果e不是l的元素,列表不被修改。该元素不能是nil。
(*List) PushBack
|
|
PushBack inserts a new element e with value v at the back of list l and returns e.
PushBack在列表l的后面插入一个新元素e,其值为v,并返回e。
(*List) PushBackList
|
|
PushBackList inserts a copy of another list at the back of list l. The lists l and other may be the same. They must not be nil.
PushBackList在列表l的后面插入一个另一个列表的副本。它们不能是nil。
(*List) PushFront
|
|
PushFront inserts a new element e with value v at the front of list l and returns e.
PushFront在列表l的前面插入一个值为v的新元素e,并返回e。
(*List) PushFrontList
|
|
PushFrontList inserts a copy of another list at the front of list l. The lists l and other may be the same. They must not be nil.
PushFrontList在列表l的前面插入一个另一个列表的副本。它们不能是nil。
(*List) Remove
|
|
Remove removes e from l if e is an element of list l. It returns the element value e.Value. The element must not be nil.
如果e是列表l的一个元素,Remove将e从l中移除,并返回元素值e.Value。该元素不能是nil。
3.3 - ring
ring
https://pkg.go.dev/container/ring@go1.20.1
Package ring implements operations on circular lists.
ring 包实现了对循环列表的操作。
常量
This section is empty.
变量
This section is empty.
函数
This section is empty.
类型
type Ring
|
|
A Ring is an element of a circular list, or ring. Rings do not have a beginning or end; a pointer to any ring element serves as reference to the entire ring. Empty rings are represented as nil Ring pointers. The zero value for a Ring is a one-element ring with a nil Value.
Ring是一个循环列表的一个元素,或者说是环。环没有开始或结束;任何环元素的指针都可以作为整个环的参考。空的环表示为nil Ring指针。一个环的零值是一个具有nil值的单元素环。
func New
|
|
New creates a ring of n elements.
New创建一个有n个元素的环。
(*Ring) Do
|
|
Do calls function f on each element of the ring, in forward order. The behavior of Do is undefined if f changes *r.
Do在环的每个元素上以正向顺序调用函数f。如果f改变了*r,Do的行为是未定义的。
Example
|
|
(*Ring) Len
|
|
Len computes the number of elements in ring r. It executes in time proportional to the number of elements.
Len计算环中元素的数量,执行时间与元素的数量成正比。
Example
|
|
(*Ring) Link
|
|
Link connects ring r with ring s such that r.Next() becomes s and returns the original value for r.Next(). r must not be empty.
Link将r环和s环连接起来,这样r.Next()就变成了s,并返回r.Next()的原始值,r不能为空。
If r and s point to the same ring, linking them removes the elements between r and s from the ring. The removed elements form a subring and the result is a reference to that subring (if no elements were removed, the result is still the original value for r.Next(), and not nil).
如果r和s指向同一个环,连接它们会从环中移除r和s之间的元素。被移除的元素形成一个子环,结果是对该子环的引用(如果没有元素被移除,结果仍然是r.Next()的原始值,而不是nil)。
If r and s point to different rings, linking them creates a single ring with the elements of s inserted after r. The result points to the element following the last element of s after insertion.
如果r和s指向不同的环,连接它们会创建一个单一的环,其中s的元素插入到r之后。
Example
|
|
(*Ring) Move
|
|
Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0) in the ring and returns that ring element. r must not be empty.
Move在环中向后(n < 0)或向前(n >= 0)移动n % r.Len()元素,并返回该环元素。
Example
|
|
(*Ring) Next
|
|
Next returns the next ring element. r must not be empty.
Next 返回下一个环状元素,r必须不是空的。
Example
|
|
(*Ring) Prev
|
|
Prev returns the previous ring element. r must not be empty.
Prev返回上一个环状元素,r不能为空。
Example
|
|
(*Ring) Unlink
|
|
Unlink removes n % r.Len() elements from the ring r, starting at r.Next(). If n % r.Len() == 0, r remains unchanged. The result is the removed subring. r must not be empty.
Unlink从r环中移除n % r.Len()元素,从r.Next()开始。如果n % r.Len() == 0,r保持不变。结果是移除的子环。
|
|
4 - crypto
4.1 - aes
aes
https://pkg.go.dev/crypto/aes@go1.20.1
Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.
The AES operations in this package are not implemented using constant-time algorithms. An exception is when running on systems with enabled hardware support for AES that makes these operations constant-time. Examples include amd64 systems using AES-NI extensions and s390x systems using Message-Security-Assist extensions. On such systems, when the result of NewCipher is passed to cipher.NewGCM, the GHASH operation used by GCM is also constant-time.
常量 ¶
const BlockSize = 16
The AES block size in bytes.
变量
This section is empty.
函数
func NewCipher ¶
func NewCipher(key []byte) (cipher.Block, error)
NewCipher creates and returns a new cipher.Block. The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
类型
type KeySizeError ¶
type KeySizeError int
(KeySizeError) Error ¶
func (k KeySizeError) Error() string
4.2 - cipher
cipher
https://pkg.go.dev/crypto/cipher@go1.20.1
Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations. See https://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html and NIST Special Publication 800-38A.
常量 ¶
This section is empty.
变量
This section is empty.
函数
This section is empty.
类型
type AEAD ¶added in go1.2
type AEAD interface {
// NonceSize returns the size of the nonce that must be passed to Seal
// and Open.
NonceSize() int
// Overhead returns the maximum difference between the lengths of a
// plaintext and its ciphertext.
Overhead() int
// Seal encrypts and authenticates plaintext, authenticates the
// additional data and appends the result to dst, returning the updated
// slice. The nonce must be NonceSize() bytes long and unique for all
// time, for a given key.
//
// To reuse plaintext's storage for the encrypted output, use plaintext[:0]
// as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
Seal(dst, nonce, plaintext, additionalData []byte) []byte
// Open decrypts and authenticates ciphertext, authenticates the
// additional data and, if successful, appends the resulting plaintext
// to dst, returning the updated slice. The nonce must be NonceSize()
// bytes long and both it and the additional data must match the
// value passed to Seal.
//
// To reuse ciphertext's storage for the decrypted output, use ciphertext[:0]
// as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
//
// Even if the function fails, the contents of dst, up to its capacity,
// may be overwritten.
Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
}
AEAD is a cipher mode providing authenticated encryption with associated data. For a description of the methodology, see https://en.wikipedia.org/wiki/Authenticated_encryption.
func NewGCM ¶added in go1.2
func NewGCM(cipher Block) (AEAD, error)
NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode with the standard nonce length.
In general, the GHASH operation performed by this implementation of GCM is not constant-time. An exception is when the underlying Block was created by aes.NewCipher on systems with hardware support for AES. See the crypto/aes package documentation for details.
func NewGCMWithNonceSize ¶added in go1.5
func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error)
NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois Counter Mode, which accepts nonces of the given length. The length must not be zero.
Only use this function if you require compatibility with an existing cryptosystem that uses non-standard nonce lengths. All other users should use NewGCM, which is faster and more resistant to misuse.
func NewGCMWithTagSize ¶added in go1.11
func NewGCMWithTagSize(cipher Block, tagSize int) (AEAD, error)
NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois Counter Mode, which generates tags with the given length.
Tag sizes between 12 and 16 bytes are allowed.
Only use this function if you require compatibility with an existing cryptosystem that uses non-standard tag lengths. All other users should use NewGCM, which is more resistant to misuse.
type Block ¶
type Block interface {
// BlockSize returns the cipher's block size.
BlockSize() int
// Encrypt encrypts the first block in src into dst.
// Dst and src must overlap entirely or not at all.
Encrypt(dst, src []byte)
// Decrypt decrypts the first block in src into dst.
// Dst and src must overlap entirely or not at all.
Decrypt(dst, src []byte)
}
A Block represents an implementation of block cipher using a given key. It provides the capability to encrypt or decrypt individual blocks. The mode implementations extend that capability to streams of blocks.
type BlockMode ¶
type BlockMode interface {
// BlockSize returns the mode's block size.
BlockSize() int
// CryptBlocks encrypts or decrypts a number of blocks. The length of
// src must be a multiple of the block size. Dst and src must overlap
// entirely or not at all.
//
// If len(dst) < len(src), CryptBlocks should panic. It is acceptable
// to pass a dst bigger than src, and in that case, CryptBlocks will
// only update dst[:len(src)] and will not touch the rest of dst.
//
// Multiple calls to CryptBlocks behave as if the concatenation of
// the src buffers was passed in a single run. That is, BlockMode
// maintains state and does not reset at each CryptBlocks call.
CryptBlocks(dst, src []byte)
}
A BlockMode represents a block cipher running in a block-based mode (CBC, ECB etc).
func NewCBCDecrypter ¶
func NewCBCDecrypter(b Block, iv []byte) BlockMode
NewCBCDecrypter returns a BlockMode which decrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block’s block size and must match the iv used to encrypt the data.
func NewCBCEncrypter ¶
func NewCBCEncrypter(b Block, iv []byte) BlockMode
NewCBCEncrypter returns a BlockMode which encrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block’s block size.
type Stream ¶
type Stream interface {
// XORKeyStream XORs each byte in the given slice with a byte from the
// cipher's key stream. Dst and src must overlap entirely or not at all.
//
// If len(dst) < len(src), XORKeyStream should panic. It is acceptable
// to pass a dst bigger than src, and in that case, XORKeyStream will
// only update dst[:len(src)] and will not touch the rest of dst.
//
// Multiple calls to XORKeyStream behave as if the concatenation of
// the src buffers was passed in a single run. That is, Stream
// maintains state and does not reset at each XORKeyStream call.
XORKeyStream(dst, src []byte)
}
A Stream represents a stream cipher.
func NewCFBDecrypter ¶
func NewCFBDecrypter(block Block, iv []byte) Stream
NewCFBDecrypter returns a Stream which decrypts with cipher feedback mode, using the given Block. The iv must be the same length as the Block’s block size.
func NewCFBEncrypter ¶
func NewCFBEncrypter(block Block, iv []byte) Stream
NewCFBEncrypter returns a Stream which encrypts with cipher feedback mode, using the given Block. The iv must be the same length as the Block’s block size.
func NewCTR ¶
func NewCTR(block Block, iv []byte) Stream
NewCTR returns a Stream which encrypts/decrypts using the given Block in counter mode. The length of iv must be the same as the Block’s block size.
func NewOFB ¶
func NewOFB(b Block, iv []byte) Stream
NewOFB returns a Stream that encrypts or decrypts using the block cipher b in output feedback mode. The initialization vector iv’s length must be equal to b’s block size.
type StreamReader ¶
type StreamReader struct {
S Stream
R io.Reader
}
StreamReader wraps a Stream into an io.Reader. It calls XORKeyStream to process each slice of data which passes through.
(StreamReader) Read ¶
func (r StreamReader) Read(dst []byte) (n int, err error)
type StreamWriter ¶
type StreamWriter struct {
S Stream
W io.Writer
Err error // unused
}
StreamWriter wraps a Stream into an io.Writer. It calls XORKeyStream to process each slice of data which passes through. If any Write call returns short then the StreamWriter is out of sync and must be discarded. A StreamWriter has no internal buffering; Close does not need to be called to flush write data.
(StreamWriter) Close ¶
func (w StreamWriter) Close() error
Close closes the underlying Writer and returns its Close return value, if the Writer is also an io.Closer. Otherwise it returns nil.
(StreamWriter) Write ¶
func (w StreamWriter) Write(src []byte) (n int, err error)
4.3 - crypto
crypto
https://pkg.go.dev/crypto@go1.20.1
Package crypto collects common cryptographic constants.
常量 ¶
This section is empty.
变量
This section is empty.
函数
func RegisterHash ¶
func RegisterHash(h Hash, f func() hash.Hash)
RegisterHash registers a function that returns a new instance of the given hash function. This is intended to be called from the init function in packages that implement hash functions.
类型
type Decrypter ¶added in go1.5
type Decrypter interface {
// Public returns the public key corresponding to the opaque,
// private key.
Public() PublicKey
// Decrypt decrypts msg. The opts argument should be appropriate for
// the primitive used. See the documentation in each implementation for
// details.
Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
}
Decrypter is an interface for an opaque private key that can be used for asymmetric decryption operations. An example would be an RSA key kept in a hardware module.
type DecrypterOpts ¶added in go1.5
type DecrypterOpts any
type Hash ¶
type Hash uint
Hash identifies a cryptographic hash function that is implemented in another package.
const (
MD4 Hash = 1 + iota // import golang.org/x/crypto/md4
MD5 // import crypto/md5
SHA1 // import crypto/sha1
SHA224 // import crypto/sha256
SHA256 // import crypto/sha256
SHA384 // import crypto/sha512
SHA512 // import crypto/sha512
MD5SHA1 // no implementation; MD5+SHA1 used for TLS RSA
RIPEMD160 // import golang.org/x/crypto/ripemd160
SHA3_224 // import golang.org/x/crypto/sha3
SHA3_256 // import golang.org/x/crypto/sha3
SHA3_384 // import golang.org/x/crypto/sha3
SHA3_512 // import golang.org/x/crypto/sha3
SHA512_224 // import crypto/sha512
SHA512_256 // import crypto/sha512
BLAKE2s_256 // import golang.org/x/crypto/blake2s
BLAKE2b_256 // import golang.org/x/crypto/blake2b
BLAKE2b_384 // import golang.org/x/crypto/blake2b
BLAKE2b_512 // import golang.org/x/crypto/blake2b
)
(Hash) Available ¶
func (h Hash) Available() bool
Available reports whether the given hash function is linked into the binary.
(Hash) HashFunc ¶added in go1.4
func (h Hash) HashFunc() Hash
HashFunc simply returns the value of h so that Hash implements SignerOpts.
(Hash) New ¶
func (h Hash) New() hash.Hash
New returns a new hash.Hash calculating the given hash function. New panics if the hash function is not linked into the binary.
(Hash) Size ¶
func (h Hash) Size() int
Size returns the length, in bytes, of a digest resulting from the given hash function. It doesn’t require that the hash function in question be linked into the program.
(Hash) String ¶added in go1.15
func (h Hash) String() string
type PrivateKey ¶
type PrivateKey any
PrivateKey represents a private key using an unspecified algorithm.
Although this type is an empty interface for backwards compatibility reasons, all private key types in the standard library implement the following interface
interface{
Public() crypto.PublicKey
Equal(x crypto.PrivateKey) bool
}
as well as purpose-specific interfaces such as Signer and Decrypter, which can be used for increased type safety within applications.
type PublicKey ¶added in go1.2
type PublicKey any
PublicKey represents a public key using an unspecified algorithm.
Although this type is an empty interface for backwards compatibility reasons, all public key types in the standard library implement the following interface
interface{
Equal(x crypto.PublicKey) bool
}
which can be used for increased type safety within applications.
type Signer ¶added in go1.4
type Signer interface {
// Public returns the public key corresponding to the opaque,
// private key.
Public() PublicKey
// Sign signs digest with the private key, possibly using entropy from
// rand. For an RSA key, the resulting signature should be either a
// PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA
// key, it should be a DER-serialised, ASN.1 signature structure.
//
// Hash implements the SignerOpts interface and, in most cases, one can
// simply pass in the hash function used as opts. Sign may also attempt
// to type assert opts to other types in order to obtain algorithm
// specific values. See the documentation in each package for details.
//
// Note that when a signature of a hash of a larger message is needed,
// the caller is responsible for hashing the larger message and passing
// the hash (as digest) and the hash function (as opts) to Sign.
Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
}
Signer is an interface for an opaque private key that can be used for signing operations. For example, an RSA key kept in a hardware module.
type SignerOpts ¶added in go1.4
type SignerOpts interface {
// HashFunc returns an identifier for the hash function used to produce
// the message passed to Signer.Sign, or else zero to indicate that no
// hashing was done.
HashFunc() Hash
}
SignerOpts contains options for signing with a Signer.
4.4 - des
des
Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.
DES is cryptographically broken and should not be used for secure applications.
常量 ¶
const BlockSize = 8
The DES block size in bytes.
变量
This section is empty.
函数
func NewCipher ¶
func NewCipher(key []byte) (cipher.Block, error)
NewCipher creates and returns a new cipher.Block.
func NewTripleDESCipher ¶
func NewTripleDESCipher(key []byte) (cipher.Block, error)
NewTripleDESCipher creates and returns a new cipher.Block.
类型
type KeySizeError ¶
type KeySizeError int
(KeySizeError) Error ¶
func (k KeySizeError) Error() string
4.5 - dsa
dsa
https://pkg.go.dev/crypto/dsa@go1.20.1
Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.
The DSA operations in this package are not implemented using constant-time algorithms.
Deprecated: DSA is a legacy algorithm, and modern alternatives such as Ed25519 (implemented by package crypto/ed25519) should be used instead. Keys with 1024-bit moduli (L1024N160 parameters) are cryptographically weak, while bigger keys are not widely supported. Note that FIPS 186-5 no longer approves DSA for signature generation.
常量 ¶
This section is empty.
变量
var ErrInvalidPublicKey = errors.New("crypto/dsa: invalid public key")
ErrInvalidPublicKey results when a public key is not usable by this code. FIPS is quite strict about the format of DSA keys, but other code may be less so. Thus, when using keys which may have been generated by other code, this error must be handled.
函数
func GenerateKey ¶
func GenerateKey(priv *PrivateKey, rand io.Reader) error
GenerateKey generates a public&private key pair. The Parameters of the PrivateKey must already be valid (see GenerateParameters).
func GenerateParameters ¶
func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) error
GenerateParameters puts a random, valid set of DSA parameters into params. This function can take many seconds, even on fast machines.
func Sign ¶
func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)
Sign signs an arbitrary length hash (which should be the result of hashing a larger message) using the private key, priv. It returns the signature as a pair of integers. The security of the private key depends on the entropy of rand.
Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated to the byte-length of the subgroup. This function does not perform that truncation itself.
Be aware that calling Sign with an attacker-controlled PrivateKey may require an arbitrary amount of CPU.
func Verify ¶
func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool
Verify verifies the signature in r, s of hash using the public key, pub. It reports whether the signature is valid.
Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated to the byte-length of the subgroup. This function does not perform that truncation itself.
类型
type ParameterSizes ¶
type ParameterSizes int
ParameterSizes is an enumeration of the acceptable bit lengths of the primes in a set of DSA parameters. See FIPS 186-3, section 4.2.
const (
L1024N160 ParameterSizes = iota
L2048N224
L2048N256
L3072N256
)
type Parameters ¶
type Parameters struct {
P, Q, G *big.Int
}
Parameters represents the domain parameters for a key. These parameters can be shared across many keys. The bit length of Q must be a multiple of 8.
type PrivateKey ¶
type PrivateKey struct {
PublicKey
X *big.Int
}
PrivateKey represents a DSA private key.
type PublicKey ¶
type PublicKey struct {
Parameters
Y *big.Int
}
PublicKey represents a DSA public key.
4.6 - ecdh
ecdh
https://pkg.go.dev/crypto/ecdh@go1.20.1
Package ecdh implements Elliptic Curve Diffie-Hellman over NIST curves and Curve25519.
常量 ¶
This section is empty.
变量
This section is empty.
函数
This section is empty.
类型
type Curve ¶
type Curve interface {
// GenerateKey generates a new PrivateKey from rand.
GenerateKey(rand io.Reader) (*PrivateKey, error)
// NewPrivateKey checks that key is valid and returns a PrivateKey.
//
// For NIST curves, this follows SEC 1, Version 2.0, Section 2.3.6, which
// amounts to decoding the bytes as a fixed length big endian integer and
// checking that the result is lower than the order of the curve. The zero
// private key is also rejected, as the encoding of the corresponding public
// key would be irregular.
//
// For X25519, this only checks the scalar length.
NewPrivateKey(key []byte) (*PrivateKey, error)
// NewPublicKey checks that key is valid and returns a PublicKey.
//
// For NIST curves, this decodes an uncompressed point according to SEC 1,
// Version 2.0, Section 2.3.4. Compressed encodings and the point at
// infinity are rejected.
//
// For X25519, this only checks the u-coordinate length. Adversarially
// selected public keys can cause ECDH to return an error.
NewPublicKey(key []byte) (*PublicKey, error)
// contains filtered or unexported methods
}
func P256 ¶
func P256() Curve
P256 returns a Curve which implements NIST P-256 (FIPS 186-3, section D.2.3), also known as secp256r1 or prime256v1.
Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.
func P384 ¶
func P384() Curve
P384 returns a Curve which implements NIST P-384 (FIPS 186-3, section D.2.4), also known as secp384r1.
Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.
func P521 ¶
func P521() Curve
P521 returns a Curve which implements NIST P-521 (FIPS 186-3, section D.2.5), also known as secp521r1.
Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.
func X25519 ¶
func X25519() Curve
X25519 returns a Curve which implements the X25519 function over Curve25519 (RFC 7748, Section 5).
Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.
type PrivateKey ¶
type PrivateKey struct {
// contains filtered or unexported fields
}
PrivateKey is an ECDH private key, usually kept secret.
These keys can be parsed with crypto/x509.ParsePKCS8PrivateKey and encoded with crypto/x509.MarshalPKCS8PrivateKey. For NIST curves, they then need to be converted with crypto/ecdsa.PrivateKey.ECDH after parsing.
(*PrivateKey) Bytes ¶
func (k *PrivateKey) Bytes() []byte
Bytes returns a copy of the encoding of the private key.
(*PrivateKey) Curve ¶
func (k *PrivateKey) Curve() Curve
(*PrivateKey) ECDH ¶
func (k *PrivateKey) ECDH(remote *PublicKey) ([]byte, error)
ECDH performs a ECDH exchange and returns the shared secret.
For NIST curves, this performs ECDH as specified in SEC 1, Version 2.0, Section 3.3.1, and returns the x-coordinate encoded according to SEC 1, Version 2.0, Section 2.3.5. The result is never the point at infinity.
For X25519, this performs ECDH as specified in RFC 7748, Section 6.1. If the result is the all-zero value, ECDH returns an error.
(*PrivateKey) Equal ¶
func (k *PrivateKey) Equal(x crypto.PrivateKey) bool
Equal returns whether x represents the same private key as k.
Note that there can be equivalent private keys with different encodings which would return false from this check but behave the same way as inputs to ECDH.
This check is performed in constant time as long as the key types and their curve match.
(*PrivateKey) Public ¶
func (k *PrivateKey) Public() crypto.PublicKey
Public implements the implicit interface of all standard library private keys. See the docs of crypto.PrivateKey.
(*PrivateKey) PublicKey ¶
func (k *PrivateKey) PublicKey() *PublicKey
type PublicKey ¶
type PublicKey struct {
// contains filtered or unexported fields
}
PublicKey is an ECDH public key, usually a peer’s ECDH share sent over the wire.
These keys can be parsed with crypto/x509.ParsePKIXPublicKey and encoded with crypto/x509.MarshalPKIXPublicKey. For NIST curves, they then need to be converted with crypto/ecdsa.PublicKey.ECDH after parsing.
(*PublicKey) Bytes ¶
func (k *PublicKey) Bytes() []byte
Bytes returns a copy of the encoding of the public key.
(*PublicKey) Curve ¶
func (k *PublicKey) Curve() Curve
(*PublicKey) Equal ¶
func (k *PublicKey) Equal(x crypto.PublicKey) bool
Equal returns whether x represents the same public key as k.
Note that there can be equivalent public keys with different encodings which would return false from this check but behave the same way as inputs to ECDH.
This check is performed in constant time as long as the key types and their curve match.
4.7 - ecdsa
ecdsa
https://pkg.go.dev/crypto/ecdsa@go1.20.1
Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-4 and SEC 1, Version 2.0.
Signatures generated by this package are not deterministic, but entropy is mixed with the private key and the message, achieving the same level of security in case of randomness source failure.
常量 ¶
This section is empty.
变量
This section is empty.
函数
func Sign ¶
func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)
Sign signs a hash (which should be the result of hashing a larger message) using the private key, priv. If the hash is longer than the bit-length of the private key’s curve order, the hash will be truncated to that length. It returns the signature as a pair of integers. Most applications should use SignASN1 instead of dealing directly with r, s.
func SignASN1 ¶added in go1.15
func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error)
SignASN1 signs a hash (which should be the result of hashing a larger message) using the private key, priv. If the hash is longer than the bit-length of the private key’s curve order, the hash will be truncated to that length. It returns the ASN.1 encoded signature.
func Verify ¶
func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool
Verify verifies the signature in r, s of hash using the public key, pub. Its return value records whether the signature is valid. Most applications should use VerifyASN1 instead of dealing directly with r, s.
func VerifyASN1 ¶added in go1.15
func VerifyASN1(pub *PublicKey, hash, sig []byte) bool
VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the public key, pub. Its return value records whether the signature is valid.
类型
type PrivateKey ¶
type PrivateKey struct {
PublicKey
D *big.Int
}
PrivateKey represents an ECDSA private key.
func GenerateKey ¶
func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error)
GenerateKey generates a public and private key pair.
(*PrivateKey) ECDH ¶added in go1.20
func (k *PrivateKey) ECDH() (*ecdh.PrivateKey, error)
ECDH returns k as a ecdh.PrivateKey. It returns an error if the key is invalid according to the definition of ecdh.Curve.NewPrivateKey, or if the Curve is not supported by crypto/ecdh.
(*PrivateKey) Equal ¶added in go1.15
func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool
Equal reports whether priv and x have the same value.
See PublicKey.Equal for details on how Curve is compared.
(*PrivateKey) Public ¶added in go1.4
func (priv *PrivateKey) Public() crypto.PublicKey
Public returns the public key corresponding to priv.
(*PrivateKey) Sign ¶added in go1.4
func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
Sign signs digest with priv, reading randomness from rand. The opts argument is not currently used but, in keeping with the crypto.Signer interface, should be the hash function used to digest the message.
This method implements crypto.Signer, which is an interface to support keys where the private part is kept in, for example, a hardware module. Common uses can use the SignASN1 function in this package directly.
type PublicKey ¶
type PublicKey struct {
elliptic.Curve
X, Y *big.Int
}
PublicKey represents an ECDSA public key.
(*PublicKey) ECDH ¶added in go1.20
func (k *PublicKey) ECDH() (*ecdh.PublicKey, error)
ECDH returns k as a ecdh.PublicKey. It returns an error if the key is invalid according to the definition of ecdh.Curve.NewPublicKey, or if the Curve is not supported by crypto/ecdh.
(*PublicKey) Equal ¶added in go1.15
func (pub *PublicKey) Equal(x crypto.PublicKey) bool
Equal reports whether pub and x have the same value.
Two keys are only considered to have the same value if they have the same Curve value. Note that for example elliptic.P256() and elliptic.P256().Params() are different values, as the latter is a generic not constant time implementation.
4.8 - ed25519
ed25519
https://pkg.go.dev/crypto/ed25519@go1.20.1
Package ed25519 implements the Ed25519 signature algorithm. See https://ed25519.cr.yp.to/.
These functions are also compatible with the “Ed25519” function defined in RFC 8032. However, unlike RFC 8032’s formulation, this package’s private key representation includes a public key suffix to make multiple signing operations with the same key more efficient. This package refers to the RFC 8032 private key as the “seed”.
Example (Ed25519ctx) ¶
常量 ¶
const (
// PublicKeySize is the size, in bytes, of public keys as used in this package.
PublicKeySize = 32
// PrivateKeySize is the size, in bytes, of private keys as used in this package.
PrivateKeySize = 64
// SignatureSize is the size, in bytes, of signatures generated and verified by this package.
SignatureSize = 64
// SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032.
SeedSize = 32
)
变量
This section is empty.
函数
func GenerateKey ¶
func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error)
GenerateKey generates a public/private key pair using entropy from rand. If rand is nil, crypto/rand.Reader will be used.
func Sign ¶
func Sign(privateKey PrivateKey, message []byte) []byte
Sign signs the message with privateKey and returns a signature. It will panic if len(privateKey) is not PrivateKeySize.
func Verify ¶
func Verify(publicKey PublicKey, message, sig []byte) bool
Verify reports whether sig is a valid signature of message by publicKey. It will panic if len(publicKey) is not PublicKeySize.
func VerifyWithOptions ¶added in go1.20
func VerifyWithOptions(publicKey PublicKey, message, sig []byte, opts *Options) error
VerifyWithOptions reports whether sig is a valid signature of message by publicKey. A valid signature is indicated by returning a nil error. It will panic if len(publicKey) is not PublicKeySize.
If opts.Hash is crypto.SHA512, the pre-hashed variant Ed25519ph is used and message is expected to be a SHA-512 hash, otherwise opts.Hash must be crypto.Hash(0) and the message must not be hashed, as Ed25519 performs two passes over messages to be signed.
类型
type Options ¶added in go1.20
type Options struct {
// Hash can be zero for regular Ed25519, or crypto.SHA512 for Ed25519ph.
Hash crypto.Hash
// Context, if not empty, selects Ed25519ctx or provides the context string
// for Ed25519ph. It can be at most 255 bytes in length.
Context string
}
Options can be used with PrivateKey.Sign or VerifyWithOptions to select Ed25519 variants.
(*Options) HashFunc ¶added in go1.20
func (o *Options) HashFunc() crypto.Hash
HashFunc returns o.Hash.
type PrivateKey ¶
type PrivateKey []byte
PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer.
func NewKeyFromSeed ¶
func NewKeyFromSeed(seed []byte) PrivateKey
NewKeyFromSeed calculates a private key from a seed. It will panic if len(seed) is not SeedSize. This function is provided for interoperability with RFC 8032. RFC 8032’s private keys correspond to seeds in this package.
(PrivateKey) Equal ¶added in go1.15
func (priv PrivateKey) Equal(x crypto.PrivateKey) bool
Equal reports whether priv and x have the same value.
(PrivateKey) Public ¶
func (priv PrivateKey) Public() crypto.PublicKey
Public returns the PublicKey corresponding to priv.
(PrivateKey) Seed ¶
func (priv PrivateKey) Seed() []byte
Seed returns the private key seed corresponding to priv. It is provided for interoperability with RFC 8032. RFC 8032’s private keys correspond to seeds in this package.
(PrivateKey) Sign ¶
func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error)
Sign signs the given message with priv. rand is ignored.
If opts.HashFunc() is crypto.SHA512, the pre-hashed variant Ed25519ph is used and message is expected to be a SHA-512 hash, otherwise opts.HashFunc() must be crypto.Hash(0) and the message must not be hashed, as Ed25519 performs two passes over messages to be signed.
A value of type Options can be used as opts, or crypto.Hash(0) or crypto.SHA512 directly to select plain Ed25519 or Ed25519ph, respectively.
type PublicKey ¶
type PublicKey []byte
PublicKey is the type of Ed25519 public keys.
(PublicKey) Equal ¶added in go1.15
func (pub PublicKey) Equal(x crypto.PublicKey) bool
Equal reports whether pub and x have the same value.
4.9 - elliptic
elliptic
https://pkg.go.dev/crypto/elliptic@go1.20.1
Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields.
The P224(), P256(), P384() and P521() values are necessary to use the crypto/ecdsa package. Most other uses should migrate to the more efficient and safer crypto/ecdh package.
常量 ¶
This section is empty.
变量
This section is empty.
函数
func GenerateKey ¶
func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err error)
GenerateKey returns a public/private key pair. The private key is generated using the given reader, which must return random data.
Note: for ECDH, use the GenerateKey methods of the crypto/ecdh package; for ECDSA, use the GenerateKey function of the crypto/ecdsa package.
func Marshal ¶
func Marshal(curve Curve, x, y *big.Int) []byte
Marshal converts a point on the curve into the uncompressed form specified in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the curve (or is the conventional point at infinity), the behavior is undefined.
Note: for ECDH, use the crypto/ecdh package. This function returns an encoding equivalent to that of PublicKey.Bytes in crypto/ecdh.
func MarshalCompressed ¶added in go1.15
func MarshalCompressed(curve Curve, x, y *big.Int) []byte
MarshalCompressed converts a point on the curve into the compressed form specified in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the curve (or is the conventional point at infinity), the behavior is undefined.
func Unmarshal ¶
func Unmarshal(curve Curve, data []byte) (x, y *big.Int)
Unmarshal converts a point, serialized by Marshal, into an x, y pair. It is an error if the point is not in uncompressed form, is not on the curve, or is the point at infinity. On error, x = nil.
Note: for ECDH, use the crypto/ecdh package. This function accepts an encoding equivalent to that of the NewPublicKey methods in crypto/ecdh.
func UnmarshalCompressed ¶added in go1.15
func UnmarshalCompressed(curve Curve, data []byte) (x, y *big.Int)
UnmarshalCompressed converts a point, serialized by MarshalCompressed, into an x, y pair. It is an error if the point is not in compressed form, is not on the curve, or is the point at infinity. On error, x = nil.
类型
type Curve ¶
type Curve interface {
// Params returns the parameters for the curve.
Params() *CurveParams
// IsOnCurve reports whether the given (x,y) lies on the curve.
//
// Note: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
// package. The NewPublicKey methods of NIST curves in crypto/ecdh accept
// the same encoding as the Unmarshal function, and perform on-curve checks.
IsOnCurve(x, y *big.Int) bool
// Add returns the sum of (x1,y1) and (x2,y2).
//
// Note: this is a low-level unsafe API.
Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int)
// Double returns 2*(x,y).
//
// Note: this is a low-level unsafe API.
Double(x1, y1 *big.Int) (x, y *big.Int)
// ScalarMult returns k*(x,y) where k is an integer in big-endian form.
//
// Note: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
// package. Most uses of ScalarMult can be replaced by a call to the ECDH
// methods of NIST curves in crypto/ecdh.
ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int)
// ScalarBaseMult returns k*G, where G is the base point of the group
// and k is an integer in big-endian form.
//
// Note: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
// package. Most uses of ScalarBaseMult can be replaced by a call to the
// PrivateKey.PublicKey method in crypto/ecdh.
ScalarBaseMult(k []byte) (x, y *big.Int)
}
A Curve represents a short-form Weierstrass curve with a=-3.
The behavior of Add, Double, and ScalarMult when the input is not a point on the curve is undefined.
Note that the conventional point at infinity (0, 0) is not considered on the curve, although it can be returned by Add, Double, ScalarMult, or ScalarBaseMult (but not the Unmarshal or UnmarshalCompressed functions).
func P224 ¶
func P224() Curve
P224 returns a Curve which implements NIST P-224 (FIPS 186-3, section D.2.2), also known as secp224r1. The CurveParams.Name of this Curve is “P-224”.
Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.
The cryptographic operations are implemented using constant-time algorithms.
func P256 ¶
func P256() Curve
P256 returns a Curve which implements NIST P-256 (FIPS 186-3, section D.2.3), also known as secp256r1 or prime256v1. The CurveParams.Name of this Curve is “P-256”.
Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.
The cryptographic operations are implemented using constant-time algorithms.
func P384 ¶
func P384() Curve
P384 returns a Curve which implements NIST P-384 (FIPS 186-3, section D.2.4), also known as secp384r1. The CurveParams.Name of this Curve is “P-384”.
Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.
The cryptographic operations are implemented using constant-time algorithms.
func P521 ¶
func P521() Curve
P521 returns a Curve which implements NIST P-521 (FIPS 186-3, section D.2.5), also known as secp521r1. The CurveParams.Name of this Curve is “P-521”.
Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.
The cryptographic operations are implemented using constant-time algorithms.
type CurveParams ¶
type CurveParams struct {
P *big.Int // the order of the underlying field
N *big.Int // the order of the base point
B *big.Int // the constant of the curve equation
Gx, Gy *big.Int // (x,y) of the base point
BitSize int // the size of the underlying field
Name string // the canonical name of the curve
}
CurveParams contains the parameters of an elliptic curve and also provides a generic, non-constant time implementation of Curve.
Note: Custom curves (those not returned by P224(), P256(), P384(), and P521()) are not guaranteed to provide any security property.
(*CurveParams) Add ¶
func (curve *CurveParams) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int)
Add implements Curve.Add.
Note: the CurveParams methods are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224(), P256(), P384(), or P521().
(*CurveParams) Double ¶
func (curve *CurveParams) Double(x1, y1 *big.Int) (*big.Int, *big.Int)
Double implements Curve.Double.
Note: the CurveParams methods are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224(), P256(), P384(), or P521().
(*CurveParams) IsOnCurve ¶
func (curve *CurveParams) IsOnCurve(x, y *big.Int) bool
IsOnCurve implements Curve.IsOnCurve.
Note: the CurveParams methods are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224(), P256(), P384(), or P521().
(*CurveParams) Params ¶
func (curve *CurveParams) Params() *CurveParams
(*CurveParams) ScalarBaseMult ¶
func (curve *CurveParams) ScalarBaseMult(k []byte) (*big.Int, *big.Int)
ScalarBaseMult implements Curve.ScalarBaseMult.
Note: the CurveParams methods are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224(), P256(), P384(), or P521().
(*CurveParams) ScalarMult ¶
func (curve *CurveParams) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int)
ScalarMult implements Curve.ScalarMult.
Note: the CurveParams methods are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224(), P256(), P384(), or P521().
4.10 - hmac
hmac
https://pkg.go.dev/crypto/hmac@go1.20.1
Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198. An HMAC is a cryptographic hash that uses a key to sign a message. The receiver verifies the hash by recomputing it using the same key.
Receivers should be careful to use Equal to compare MACs in order to avoid timing side-channels:
// ValidMAC reports whether messageMAC is a valid HMAC tag for message.
func ValidMAC(message, messageMAC, key []byte) bool {
mac := hmac.New(sha256.New, key)
mac.Write(message)
expectedMAC := mac.Sum(nil)
return hmac.Equal(messageMAC, expectedMAC)
}
常量 ¶
This section is empty.
变量
This section is empty.
函数
func Equal ¶added in go1.1
func Equal(mac1, mac2 []byte) bool
Equal compares two MACs for equality without leaking timing information.
func New ¶
func New(h func() hash.Hash, key []byte) hash.Hash
New returns a new HMAC hash using the given hash.Hash type and key. New functions like sha256.New from crypto/sha256 can be used as h. h must return a new Hash every time it is called. Note that unlike other hash implementations in the standard library, the returned Hash does not implement encoding.BinaryMarshaler or encoding.BinaryUnmarshaler.
类型
This section is empty.
4.11 - md5
md5
https://pkg.go.dev/crypto/md5@go1.20.1
Package md5 implements the MD5 hash algorithm as defined in RFC 1321.
MD5 is cryptographically broken and should not be used for secure applications.
常量 ¶
const BlockSize = 64
The blocksize of MD5 in bytes.
const Size = 16
The size of an MD5 checksum in bytes.
变量
This section is empty.
函数
func New ¶
func New() hash.Hash
New returns a new hash.Hash computing the MD5 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.
func Sum ¶added in go1.2
func Sum(data []byte) [Size]byte
Sum returns the MD5 checksum of the data.
类型
This section is empty.
4.12 - rand
rand
https://pkg.go.dev/crypto/rand@go1.20.1
Package rand implements a cryptographically secure random number generator.
常量 ¶
This section is empty.
变量
var Reader io.Reader
Reader is a global, shared instance of a cryptographically secure random number generator.
On Linux, FreeBSD, Dragonfly and Solaris, Reader uses getrandom(2) if available, /dev/urandom otherwise. On OpenBSD and macOS, Reader uses getentropy(2). On other Unix-like systems, Reader reads from /dev/urandom. On Windows systems, Reader uses the RtlGenRandom API. On Wasm, Reader uses the Web Crypto API.
函数
func Int ¶
func Int(rand io.Reader, max *big.Int) (n *big.Int, err error)
Int returns a uniform random value in [0, max). It panics if max <= 0.
func Prime ¶
func Prime(rand io.Reader, bits int) (*big.Int, error)
Prime returns a number of the given bit length that is prime with high probability. Prime will return error for any error returned by rand.Read or if bits < 2.
func Read ¶
func Read(b []byte) (n int, err error)
Read is a helper function that calls Reader.Read using io.ReadFull. On return, n == len(b) if and only if err == nil.
类型
This section is empty.
4.13 - rc4
rc4
https://pkg.go.dev/crypto/rc4@go1.20.1
Package rc4 implements RC4 encryption, as defined in Bruce Schneier’s Applied Cryptography.
RC4 is cryptographically broken and should not be used for secure applications.
常量 ¶
This section is empty.
变量
This section is empty.
函数
This section is empty.
类型
type Cipher ¶
type Cipher struct {
// contains filtered or unexported fields
}
A Cipher is an instance of RC4 using a particular key.
func NewCipher ¶
func NewCipher(key []byte) (*Cipher, error)
NewCipher creates and returns a new Cipher. The key argument should be the RC4 key, at least 1 byte and at most 256 bytes.
func (*Cipher)ResetDEPRECATED
(*Cipher) XORKeyStream ¶
func (c *Cipher) XORKeyStream(dst, src []byte)
XORKeyStream sets dst to the result of XORing src with the key stream. Dst and src must overlap entirely or not at all.
type KeySizeError ¶
type KeySizeError int
(KeySizeError) Error ¶
func (k KeySizeError) Error() string
4.14 - rsa
rsa
https://pkg.go.dev/crypto/rsa@go1.20.1
Package rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.
RSA is a single, fundamental operation that is used in this package to implement either public-key encryption or public-key signatures.
The original specification for encryption and signatures with RSA is PKCS #1 and the terms “RSA encryption” and “RSA signatures” by default refer to PKCS #1 version 1.5. However, that specification has flaws and new designs should use version 2, usually called by just OAEP and PSS, where possible.
Two sets of interfaces are included in this package. When a more abstract interface isn’t necessary, there are functions for encrypting/decrypting with v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstract over the public key primitive, the PrivateKey type implements the Decrypter and Signer interfaces from the crypto package.
Operations in this package are implemented using constant-time algorithms, except for GenerateKey, PrivateKey.Precompute, and PrivateKey.Validate. Every other operation only leaks the bit size of the involved values, which all depend on the selected key size.
常量 ¶
const (
// PSSSaltLengthAuto causes the salt in a PSS signature to be as large
// as possible when signing, and to be auto-detected when verifying.
PSSSaltLengthAuto = 0
// PSSSaltLengthEqualsHash causes the salt length to equal the length
// of the hash used in the signature.
PSSSaltLengthEqualsHash = -1
)
变量
var ErrDecryption = errors.New("crypto/rsa: decryption error")
ErrDecryption represents a failure to decrypt a message. It is deliberately vague to avoid adaptive attacks.
var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA key size")
ErrMessageTooLong is returned when attempting to encrypt or sign a message which is too large for the size of the key. When using SignPSS, this can also be returned if the size of the salt is too large.
var ErrVerification = errors.New("crypto/rsa: verification error")
ErrVerification represents a failure to verify a signature. It is deliberately vague to avoid adaptive attacks.
函数
func DecryptOAEP ¶
func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error)
DecryptOAEP decrypts ciphertext using RSA-OAEP.
OAEP is parameterised by a hash function that is used as a random oracle. Encryption and decryption of a given message must use the same hash function and sha256.New() is a reasonable choice.
The random parameter is legacy and ignored, and it can be as nil.
The label parameter must match the value given when encrypting. See EncryptOAEP for details.
Example ¶
func DecryptPKCS1v15 ¶
func DecryptPKCS1v15(random io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error)
DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and it can be as nil.
Note that whether this function returns an error or not discloses secret information. If an attacker can cause this function to run repeatedly and learn whether each instance returned an error then they can decrypt and forge signatures as if they had the private key. See DecryptPKCS1v15SessionKey for a way of solving this problem.
func DecryptPKCS1v15SessionKey ¶
func DecryptPKCS1v15SessionKey(random io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error
DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and it can be as nil. It returns an error if the ciphertext is the wrong length or if the ciphertext is greater than the public modulus. Otherwise, no error is returned. If the padding is valid, the resulting plaintext message is copied into key. Otherwise, key is unchanged. These alternatives occur in constant time. It is intended that the user of this function generate a random session key beforehand and continue the protocol with the resulting value. This will remove any possibility that an attacker can learn any information about the plaintext. See “Chosen Ciphertext Attacks Against Protocols Based on the RSA Encryption Standard PKCS #1”, Daniel Bleichenbacher, Advances in Cryptology (Crypto ‘98).
Note that if the session key is too small then it may be possible for an attacker to brute-force it. If they can do that then they can learn whether a random value was used (because it’ll be different for the same ciphertext) and thus whether the padding was correct. This defeats the point of this function. Using at least a 16-byte key will protect against this attack.
Example ¶
func EncryptOAEP ¶
func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error)
EncryptOAEP encrypts the given message with RSA-OAEP.
OAEP is parameterised by a hash function that is used as a random oracle. Encryption and decryption of a given message must use the same hash function and sha256.New() is a reasonable choice.
The random parameter is used as a source of entropy to ensure that encrypting the same message twice doesn’t result in the same ciphertext.
The label parameter may contain arbitrary data that will not be encrypted, but which gives important context to the message. For example, if a given public key is used to encrypt two types of messages then distinct label values could be used to ensure that a ciphertext for one purpose cannot be used for another by an attacker. If not required it can be empty.
The message must be no longer than the length of the public modulus minus twice the hash length, minus a further 2.
Example ¶
func EncryptPKCS1v15 ¶
func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error)
EncryptPKCS1v15 encrypts the given message with RSA and the padding scheme from PKCS #1 v1.5. The message must be no longer than the length of the public modulus minus 11 bytes.
The random parameter is used as a source of entropy to ensure that encrypting the same message twice doesn’t result in the same ciphertext.
WARNING: use of this function to encrypt plaintexts other than session keys is dangerous. Use RSA OAEP in new protocols.
func SignPKCS1v15 ¶
func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error)
SignPKCS1v15 calculates the signature of hashed using RSASSA-PKCS1-V1_5-SIGN from RSA PKCS #1 v1.5. Note that hashed must be the result of hashing the input message using the given hash function. If hash is zero, hashed is signed directly. This isn’t advisable except for interoperability.
The random parameter is legacy and ignored, and it can be as nil.
This function is deterministic. Thus, if the set of possible messages is small, an attacker may be able to build a map from messages to signatures and identify the signed messages. As ever, signatures provide authenticity, not confidentiality.
Example ¶
func SignPSS ¶added in go1.2
func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, digest []byte, opts *PSSOptions) ([]byte, error)
SignPSS calculates the signature of digest using PSS.
digest must be the result of hashing the input message using the given hash function. The opts argument may be nil, in which case sensible defaults are used. If opts.Hash is set, it overrides hash.
func VerifyPKCS1v15 ¶
func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error
VerifyPKCS1v15 verifies an RSA PKCS #1 v1.5 signature. hashed is the result of hashing the input message using the given hash function and sig is the signature. A valid signature is indicated by returning a nil error. If hash is zero then hashed is used directly. This isn’t advisable except for interoperability.
Example ¶
func VerifyPSS ¶added in go1.2
func VerifyPSS(pub *PublicKey, hash crypto.Hash, digest []byte, sig []byte, opts *PSSOptions) error
VerifyPSS verifies a PSS signature.
A valid signature is indicated by returning a nil error. digest must be the result of hashing the input message using the given hash function. The opts argument may be nil, in which case sensible defaults are used. opts.Hash is ignored.
类型
type CRTValue ¶
type CRTValue struct {
Exp *big.Int // D mod (prime-1).
Coeff *big.Int // R·Coeff ≡ 1 mod Prime.
R *big.Int // product of primes prior to this (inc p and q).
}
CRTValue contains the precomputed Chinese remainder theorem values.
type OAEPOptions ¶added in go1.5
type OAEPOptions struct {
// Hash is the hash function that will be used when generating the mask.
Hash crypto.Hash
// MGFHash is the hash function used for MGF1.
// If zero, Hash is used instead.
MGFHash crypto.Hash
// Label is an arbitrary byte string that must be equal to the value
// used when encrypting.
Label []byte
}
OAEPOptions is an interface for passing options to OAEP decryption using the crypto.Decrypter interface.
type PKCS1v15DecryptOptions ¶added in go1.5
type PKCS1v15DecryptOptions struct {
// SessionKeyLen is the length of the session key that is being
// decrypted. If not zero, then a padding error during decryption will
// cause a random plaintext of this length to be returned rather than
// an error. These alternatives happen in constant time.
SessionKeyLen int
}
PKCS1v15DecryptOptions is for passing options to PKCS #1 v1.5 decryption using the crypto.Decrypter interface.
type PSSOptions ¶added in go1.2
type PSSOptions struct {
// SaltLength controls the length of the salt used in the PSS signature. It
// can either be a positive number of bytes, or one of the special
// PSSSaltLength constants.
SaltLength int
// Hash is the hash function used to generate the message digest. If not
// zero, it overrides the hash function passed to SignPSS. It's required
// when using PrivateKey.Sign.
Hash crypto.Hash
}
PSSOptions contains options for creating and verifying PSS signatures.
(*PSSOptions) HashFunc ¶added in go1.4
func (opts *PSSOptions) HashFunc() crypto.Hash
HashFunc returns opts.Hash so that PSSOptions implements crypto.SignerOpts.
type PrecomputedValues ¶
type PrecomputedValues struct {
Dp, Dq *big.Int // D mod (P-1) (or mod Q-1)
Qinv *big.Int // Q^-1 mod P
// CRTValues is used for the 3rd and subsequent primes. Due to a
// historical accident, the CRT for the first two primes is handled
// differently in PKCS #1 and interoperability is sufficiently
// important that we mirror this.
//
// Note: these values are still filled in by Precompute for
// backwards compatibility but are not used. Multi-prime RSA is very rare,
// and is implemented by this package without CRT optimizations to limit
// complexity.
CRTValues []CRTValue
// contains filtered or unexported fields
}
type PrivateKey ¶
type PrivateKey struct {
PublicKey // public part.
D *big.Int // private exponent
Primes []*big.Int // prime factors of N, has >= 2 elements.
// Precomputed contains precomputed values that speed up RSA operations,
// if available. It must be generated by calling PrivateKey.Precompute and
// must not be modified.
Precomputed PrecomputedValues
}
A PrivateKey represents an RSA key
func GenerateKey ¶
func GenerateKey(random io.Reader, bits int) (*PrivateKey, error)
GenerateKey generates an RSA keypair of the given bit size using the random source random (for example, crypto/rand.Reader).
func GenerateMultiPrimeKey ¶
func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error)
GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit size and the given random source.
Table 1 in “On the Security of Multi-prime RSA” suggests maximum numbers of primes for a given bit size.
Although the public keys are compatible (actually, indistinguishable) from the 2-prime case, the private keys are not. Thus it may not be possible to export multi-prime private keys in certain formats or to subsequently import them into other code.
This package does not implement CRT optimizations for multi-prime RSA, so the keys with more than two primes will have worse performance.
Note: The use of this function with a number of primes different from two is not recommended for the above security, compatibility, and performance reasons. Use GenerateKey instead.
(*PrivateKey) Decrypt ¶added in go1.5
func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)
Decrypt decrypts ciphertext with priv. If opts is nil or of type *PKCS1v15DecryptOptions then PKCS #1 v1.5 decryption is performed. Otherwise opts must have type *OAEPOptions and OAEP decryption is done.
(*PrivateKey) Equal ¶added in go1.15
func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool
Equal reports whether priv and x have equivalent values. It ignores Precomputed values.
(*PrivateKey) Precompute ¶
func (priv *PrivateKey) Precompute()
Precompute performs some calculations that speed up private key operations in the future.
(*PrivateKey) Public ¶added in go1.4
func (priv *PrivateKey) Public() crypto.PublicKey
Public returns the public key corresponding to priv.
(*PrivateKey) Sign ¶added in go1.4
func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
Sign signs digest with priv, reading randomness from rand. If opts is a *PSSOptions then the PSS algorithm will be used, otherwise PKCS #1 v1.5 will be used. digest must be the result of hashing the input message using opts.HashFunc().
This method implements crypto.Signer, which is an interface to support keys where the private part is kept in, for example, a hardware module. Common uses should use the Sign* functions in this package directly.
(*PrivateKey) Validate ¶
func (priv *PrivateKey) Validate() error
Validate performs basic sanity checks on the key. It returns nil if the key is valid, or else an error describing a problem.
type PublicKey ¶
type PublicKey struct {
N *big.Int // modulus
E int // public exponent
}
A PublicKey represents the public part of an RSA key.
(*PublicKey) Equal ¶added in go1.15
func (pub *PublicKey) Equal(x crypto.PublicKey) bool
Equal reports whether pub and x have the same value.
(*PublicKey) Size ¶added in go1.11
func (pub *PublicKey) Size() int
Size returns the modulus size in bytes. Raw signatures and ciphertexts for or by this public key will have the same size.
4.15 - sha1
sha1
https://pkg.go.dev/crypto/sha1@go1.20.1
Package sha1 implements the SHA-1 hash algorithm as defined in RFC 3174.
SHA-1 is cryptographically broken and should not be used for secure applications.
常量 ¶
const BlockSize = 64
The blocksize of SHA-1 in bytes.
const Size = 20
The size of a SHA-1 checksum in bytes.
变量
This section is empty.
函数
func New ¶
func New() hash.Hash
New returns a new hash.Hash computing the SHA1 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.
func Sum ¶added in go1.2
func Sum(data []byte) [Size]byte
Sum returns the SHA-1 checksum of the data.
类型
This section is empty.
4.16 - sha256
sha256
https://pkg.go.dev/crypto/sha256@go1.20.1
Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
常量 ¶
const BlockSize = 64
The blocksize of SHA256 and SHA224 in bytes.
const Size = 32
The size of a SHA256 checksum in bytes.
const Size224 = 28
The size of a SHA224 checksum in bytes.
变量
This section is empty.
函数
func New ¶
func New() hash.Hash
New returns a new hash.Hash computing the SHA256 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.
func New224 ¶
func New224() hash.Hash
New224 returns a new hash.Hash computing the SHA224 checksum.
func Sum224 ¶added in go1.2
func Sum224(data []byte) [Size224]byte
Sum224 returns the SHA224 checksum of the data.
func Sum256 ¶added in go1.2
func Sum256(data []byte) [Size]byte
Sum256 returns the SHA256 checksum of the data.
类型
This section is empty.
4.17 - sha512
sha512
https://pkg.go.dev/crypto/sha512@go1.20.1
Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.
All the hash.Hash implementations returned by this package also implement encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.
常量 ¶
const (
// Size is the size, in bytes, of a SHA-512 checksum.
Size = 64
// Size224 is the size, in bytes, of a SHA-512/224 checksum.
Size224 = 28
// Size256 is the size, in bytes, of a SHA-512/256 checksum.
Size256 = 32
// Size384 is the size, in bytes, of a SHA-384 checksum.
Size384 = 48
// BlockSize is the block size, in bytes, of the SHA-512/224,
// SHA-512/256, SHA-384 and SHA-512 hash functions.
BlockSize = 128
)
变量
This section is empty.
函数
func New ¶
func New() hash.Hash
New returns a new hash.Hash computing the SHA-512 checksum.
func New384 ¶
func New384() hash.Hash
New384 returns a new hash.Hash computing the SHA-384 checksum.
func New512_224 ¶added in go1.5
func New512_224() hash.Hash
New512_224 returns a new hash.Hash computing the SHA-512/224 checksum.
func New512_256 ¶added in go1.5
func New512_256() hash.Hash
New512_256 returns a new hash.Hash computing the SHA-512/256 checksum.
func Sum384 ¶added in go1.2
func Sum384(data []byte) [Size384]byte
Sum384 returns the SHA384 checksum of the data.
func Sum512 ¶added in go1.2
func Sum512(data []byte) [Size]byte
Sum512 returns the SHA512 checksum of the data.
func Sum512_224 ¶added in go1.5
func Sum512_224(data []byte) [Size224]byte
Sum512_224 returns the Sum512/224 checksum of the data.
func Sum512_256 ¶added in go1.5
func Sum512_256(data []byte) [Size256]byte
Sum512_256 returns the Sum512/256 checksum of the data.
类型
This section is empty.
4.18 - subtle
subtle
https://pkg.go.dev/crypto/subtle@go1.20.1
Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.
常量 ¶
This section is empty.
变量
This section is empty.
函数
func ConstantTimeByteEq ¶
func ConstantTimeByteEq(x, y uint8) int
ConstantTimeByteEq returns 1 if x == y and 0 otherwise.
func ConstantTimeCompare ¶
func ConstantTimeCompare(x, y []byte) int
ConstantTimeCompare returns 1 if the two slices, x and y, have equal contents and 0 otherwise. The time taken is a function of the length of the slices and is independent of the contents. If the lengths of x and y do not match it returns 0 immediately.
func ConstantTimeCopy ¶
func ConstantTimeCopy(v int, x, y []byte)
ConstantTimeCopy copies the contents of y into x (a slice of equal length) if v == 1. If v == 0, x is left unchanged. Its behavior is undefined if v takes any other value.
func ConstantTimeEq ¶
func ConstantTimeEq(x, y int32) int
ConstantTimeEq returns 1 if x == y and 0 otherwise.
func ConstantTimeLessOrEq ¶added in go1.2
func ConstantTimeLessOrEq(x, y int) int
ConstantTimeLessOrEq returns 1 if x <= y and 0 otherwise. Its behavior is undefined if x or y are negative or > 2**31 - 1.
func ConstantTimeSelect ¶
func ConstantTimeSelect(v, x, y int) int
ConstantTimeSelect returns x if v == 1 and y if v == 0. Its behavior is undefined if v takes any other value.
func XORBytes ¶added in go1.20
func XORBytes(dst, x, y []byte) int
XORBytes sets dst[i] = x[i] ^ y[i] for all i < n = min(len(x), len(y)), returning n, the number of bytes written to dst. If dst does not have length at least n, XORBytes panics without writing anything to dst.
类型
This section is empty.
4.19 - tls
tls
https://pkg.go.dev/crypto/tls@go1.20.1
Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
常量 ¶
const (
// TLS 1.0 - 1.2 cipher suites.
TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005
TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000a
TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002f
TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035
TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003c
TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009c
TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009d
TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xc007
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xc009
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xc00a
TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xc011
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xc013
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xc014
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc023
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc027
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02f
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc030
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc02c
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca8
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9
// TLS 1.3 cipher suites.
TLS_AES_128_GCM_SHA256 uint16 = 0x1301
TLS_AES_256_GCM_SHA384 uint16 = 0x1302
TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303
// TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
// that the client is doing version fallback. See RFC 7507.
TLS_FALLBACK_SCSV uint16 = 0x5600
// Legacy names for the corresponding cipher suites with the correct _SHA256
// suffix, retained for backward compatibility.
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
)
A list of cipher suite IDs that are, or have been, implemented by this package.
See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml
const (
VersionTLS10 = 0x0301
VersionTLS11 = 0x0302
VersionTLS12 = 0x0303
VersionTLS13 = 0x0304
// Deprecated: SSLv3 is cryptographically broken, and is no longer
// supported by this package. See golang.org/issue/32716.
VersionSSL30 = 0x0300
)
变量
This section is empty.
函数
func CipherSuiteName ¶added in go1.14
func CipherSuiteName(id uint16) string
CipherSuiteName returns the standard name for the passed cipher suite ID (e.g. “TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256”), or a fallback representation of the ID value if the cipher suite is not implemented by this package.
func Listen ¶
func Listen(network, laddr string, config *Config) (net.Listener, error)
Listen creates a TLS listener accepting connections on the given network address using net.Listen. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.
func NewListener ¶
func NewListener(inner net.Listener, config *Config) net.Listener
NewListener creates a Listener which accepts connections from an inner Listener and wraps each connection with Server. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.
类型
type Certificate ¶
type Certificate struct {
Certificate [][]byte
// PrivateKey contains the private key corresponding to the public key in
// Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
// For a server up to TLS 1.2, it can also implement crypto.Decrypter with
// an RSA PublicKey.
PrivateKey crypto.PrivateKey
// SupportedSignatureAlgorithms is an optional list restricting what
// signature algorithms the PrivateKey can be used for.
SupportedSignatureAlgorithms []SignatureScheme
// OCSPStaple contains an optional OCSP response which will be served
// to clients that request it.
OCSPStaple []byte
// SignedCertificateTimestamps contains an optional list of Signed
// Certificate Timestamps which will be served to clients that request it.
SignedCertificateTimestamps [][]byte
// Leaf is the parsed form of the leaf certificate, which may be initialized
// using x509.ParseCertificate to reduce per-handshake processing. If nil,
// the leaf certificate will be parsed as needed.
Leaf *x509.Certificate
}
A Certificate is a chain of one or more certificates, leaf first.
func LoadX509KeyPair ¶
func LoadX509KeyPair(certFile, keyFile string) (Certificate, error)
LoadX509KeyPair reads and parses a public/private key pair from a pair of files. The files must contain PEM encoded data. The certificate file may contain intermediate certificates following the leaf certificate to form a certificate chain. On successful return, Certificate.Leaf will be nil because the parsed form of the certificate is not retained.
func X509KeyPair ¶
func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)
X509KeyPair parses a public/private key pair from a pair of PEM encoded data. On successful return, Certificate.Leaf will be nil because the parsed form of the certificate is not retained.
type CertificateRequestInfo ¶added in go1.8
type CertificateRequestInfo struct {
// AcceptableCAs contains zero or more, DER-encoded, X.501
// Distinguished Names. These are the names of root or intermediate CAs
// that the server wishes the returned certificate to be signed by. An
// empty slice indicates that the server has no preference.
AcceptableCAs [][]byte
// SignatureSchemes lists the signature schemes that the server is
// willing to verify.
SignatureSchemes []SignatureScheme
// Version is the TLS version that was negotiated for this connection.
Version uint16
// contains filtered or unexported fields
}
CertificateRequestInfo contains information from a server’s CertificateRequest message, which is used to demand a certificate and proof of control from a client.
(*CertificateRequestInfo) Context ¶added in go1.17
func (c *CertificateRequestInfo) Context() context.Context
Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.
(*CertificateRequestInfo) SupportsCertificate ¶added in go1.14
func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error
SupportsCertificate returns nil if the provided certificate is supported by the server that sent the CertificateRequest. Otherwise, it returns an error describing the reason for the incompatibility.
type CertificateVerificationError ¶added in go1.20
type CertificateVerificationError struct {
// UnverifiedCertificates and its contents should not be modified.
UnverifiedCertificates []*x509.Certificate
Err error
}
CertificateVerificationError is returned when certificate verification fails during the handshake.
(*CertificateVerificationError) Error ¶added in go1.20
func (e *CertificateVerificationError) Error() string
(*CertificateVerificationError) Unwrap ¶added in go1.20
func (e *CertificateVerificationError) Unwrap() error
type CipherSuite ¶added in go1.14
type CipherSuite struct {
ID uint16
Name string
// Supported versions is the list of TLS protocol versions that can
// negotiate this cipher suite.
SupportedVersions []uint16
// Insecure is true if the cipher suite has known security issues
// due to its primitives, design, or implementation.
Insecure bool
}
CipherSuite is a TLS cipher suite. Note that most functions in this package accept and expose cipher suite IDs instead of this type.
func CipherSuites ¶added in go1.14
func CipherSuites() []*CipherSuite
CipherSuites returns a list of cipher suites currently implemented by this package, excluding those with security issues, which are returned by InsecureCipherSuites.
The list is sorted by ID. Note that the default cipher suites selected by this package might depend on logic that can’t be captured by a static list, and might not match those returned by this function.
func InsecureCipherSuites ¶added in go1.14
func InsecureCipherSuites() []*CipherSuite
InsecureCipherSuites returns a list of cipher suites currently implemented by this package and which have security issues.
Most applications should not use the cipher suites in this list, and should only use those returned by CipherSuites.
type ClientAuthType ¶
type ClientAuthType int
ClientAuthType declares the policy the server will follow for TLS Client Authentication.
const (
// NoClientCert indicates that no client certificate should be requested
// during the handshake, and if any certificates are sent they will not
// be verified.
NoClientCert ClientAuthType = iota
// RequestClientCert indicates that a client certificate should be requested
// during the handshake, but does not require that the client send any
// certificates.
RequestClientCert
// RequireAnyClientCert indicates that a client certificate should be requested
// during the handshake, and that at least one certificate is required to be
// sent by the client, but that certificate is not required to be valid.
RequireAnyClientCert
// VerifyClientCertIfGiven indicates that a client certificate should be requested
// during the handshake, but does not require that the client sends a
// certificate. If the client does send a certificate it is required to be
// valid.
VerifyClientCertIfGiven
// RequireAndVerifyClientCert indicates that a client certificate should be requested
// during the handshake, and that at least one valid certificate is required
// to be sent by the client.
RequireAndVerifyClientCert
)
(ClientAuthType) String ¶added in go1.15
func (i ClientAuthType) String() string
type ClientHelloInfo ¶added in go1.4
type ClientHelloInfo struct {
// CipherSuites lists the CipherSuites supported by the client (e.g.
// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
CipherSuites []uint16
// ServerName indicates the name of the server requested by the client
// in order to support virtual hosting. ServerName is only set if the
// client is using SNI (see RFC 4366, Section 3.1).
ServerName string
// SupportedCurves lists the elliptic curves supported by the client.
// SupportedCurves is set only if the Supported Elliptic Curves
// Extension is being used (see RFC 4492, Section 5.1.1).
SupportedCurves []CurveID
// SupportedPoints lists the point formats supported by the client.
// SupportedPoints is set only if the Supported Point Formats Extension
// is being used (see RFC 4492, Section 5.1.2).
SupportedPoints []uint8
// SignatureSchemes lists the signature and hash schemes that the client
// is willing to verify. SignatureSchemes is set only if the Signature
// Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
SignatureSchemes []SignatureScheme
// SupportedProtos lists the application protocols supported by the client.
// SupportedProtos is set only if the Application-Layer Protocol
// Negotiation Extension is being used (see RFC 7301, Section 3.1).
//
// Servers can select a protocol by setting Config.NextProtos in a
// GetConfigForClient return value.
SupportedProtos []string
// SupportedVersions lists the TLS versions supported by the client.
// For TLS versions less than 1.3, this is extrapolated from the max
// version advertised by the client, so values other than the greatest
// might be rejected if used.
SupportedVersions []uint16
// Conn is the underlying net.Conn for the connection. Do not read
// from, or write to, this connection; that will cause the TLS
// connection to fail.
Conn net.Conn
// contains filtered or unexported fields
}
ClientHelloInfo contains information from a ClientHello message in order to guide application logic in the GetCertificate and GetConfigForClient callbacks.
(*ClientHelloInfo) Context ¶added in go1.17
func (c *ClientHelloInfo) Context() context.Context
Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.
(*ClientHelloInfo) SupportsCertificate ¶added in go1.14
func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error
SupportsCertificate returns nil if the provided certificate is supported by the client that sent the ClientHello. Otherwise, it returns an error describing the reason for the incompatibility.
If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate callback, this method will take into account the associated Config. Note that if GetConfigForClient returns a different Config, the change can’t be accounted for by this method.
This function will call x509.ParseCertificate unless c.Leaf is set, which can incur a significant performance cost.
type ClientSessionCache ¶added in go1.3
type ClientSessionCache interface {
// Get searches for a ClientSessionState associated with the given key.
// On return, ok is true if one was found.
Get(sessionKey string) (session *ClientSessionState, ok bool)
// Put adds the ClientSessionState to the cache with the given key. It might
// get called multiple times in a connection if a TLS 1.3 server provides
// more than one session ticket. If called with a nil *ClientSessionState,
// it should remove the cache entry.
Put(sessionKey string, cs *ClientSessionState)
}
ClientSessionCache is a cache of ClientSessionState objects that can be used by a client to resume a TLS session with a given server. ClientSessionCache implementations should expect to be called concurrently from different goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which are supported via this interface.
func NewLRUClientSessionCache ¶added in go1.3
func NewLRUClientSessionCache(capacity int) ClientSessionCache
NewLRUClientSessionCache returns a ClientSessionCache with the given capacity that uses an LRU strategy. If capacity is < 1, a default capacity is used instead.
type ClientSessionState ¶added in go1.3
type ClientSessionState struct {
// contains filtered or unexported fields
}
ClientSessionState contains the state needed by clients to resume TLS sessions.
type Config ¶
type Config struct {
// Rand provides the source of entropy for nonces and RSA blinding.
// If Rand is nil, TLS uses the cryptographic random reader in package
// crypto/rand.
// The Reader must be safe for use by multiple goroutines.
Rand io.Reader
// Time returns the current time as the number of seconds since the epoch.
// If Time is nil, TLS uses time.Now.
Time func() time.Time
// Certificates contains one or more certificate chains to present to the
// other side of the connection. The first certificate compatible with the
// peer's requirements is selected automatically.
//
// Server configurations must set one of Certificates, GetCertificate or
// GetConfigForClient. Clients doing client-authentication may set either
// Certificates or GetClientCertificate.
//
// Note: if there are multiple Certificates, and they don't have the
// optional field Leaf set, certificate selection will incur a significant
// per-handshake performance cost.
Certificates []Certificate
// NameToCertificate maps from a certificate name to an element of
// Certificates. Note that a certificate name can be of the form
// '*.example.com' and so doesn't have to be a domain name as such.
//
// Deprecated: NameToCertificate only allows associating a single
// certificate with a given name. Leave this field nil to let the library
// select the first compatible chain from Certificates.
NameToCertificate map[string]*Certificate
// GetCertificate returns a Certificate based on the given
// ClientHelloInfo. It will only be called if the client supplies SNI
// information or if Certificates is empty.
//
// If GetCertificate is nil or returns nil, then the certificate is
// retrieved from NameToCertificate. If NameToCertificate is nil, the
// best element of Certificates will be used.
//
// Once a Certificate is returned it should not be modified.
GetCertificate func(*ClientHelloInfo) (*Certificate, error)
// GetClientCertificate, if not nil, is called when a server requests a
// certificate from a client. If set, the contents of Certificates will
// be ignored.
//
// If GetClientCertificate returns an error, the handshake will be
// aborted and that error will be returned. Otherwise
// GetClientCertificate must return a non-nil Certificate. If
// Certificate.Certificate is empty then no certificate will be sent to
// the server. If this is unacceptable to the server then it may abort
// the handshake.
//
// GetClientCertificate may be called multiple times for the same
// connection if renegotiation occurs or if TLS 1.3 is in use.
//
// Once a Certificate is returned it should not be modified.
GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
// GetConfigForClient, if not nil, is called after a ClientHello is
// received from a client. It may return a non-nil Config in order to
// change the Config that will be used to handle this connection. If
// the returned Config is nil, the original Config will be used. The
// Config returned by this callback may not be subsequently modified.
//
// If GetConfigForClient is nil, the Config passed to Server() will be
// used for all connections.
//
// If SessionTicketKey was explicitly set on the returned Config, or if
// SetSessionTicketKeys was called on the returned Config, those keys will
// be used. Otherwise, the original Config keys will be used (and possibly
// rotated if they are automatically managed).
GetConfigForClient func(*ClientHelloInfo) (*Config, error)
// VerifyPeerCertificate, if not nil, is called after normal
// certificate verification by either a TLS client or server. It
// receives the raw ASN.1 certificates provided by the peer and also
// any verified chains that normal processing found. If it returns a
// non-nil error, the handshake is aborted and that error results.
//
// If normal verification fails then the handshake will abort before
// considering this callback. If normal verification is disabled by
// setting InsecureSkipVerify, or (for a server) when ClientAuth is
// RequestClientCert or RequireAnyClientCert, then this callback will
// be considered but the verifiedChains argument will always be nil.
//
// verifiedChains and its contents should not be modified.
VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
// VerifyConnection, if not nil, is called after normal certificate
// verification and after VerifyPeerCertificate by either a TLS client
// or server. If it returns a non-nil error, the handshake is aborted
// and that error results.
//
// If normal verification fails then the handshake will abort before
// considering this callback. This callback will run for all connections
// regardless of InsecureSkipVerify or ClientAuth settings.
VerifyConnection func(ConnectionState) error
// RootCAs defines the set of root certificate authorities
// that clients use when verifying server certificates.
// If RootCAs is nil, TLS uses the host's root CA set.
RootCAs *x509.CertPool
// NextProtos is a list of supported application level protocols, in
// order of preference. If both peers support ALPN, the selected
// protocol will be one from this list, and the connection will fail
// if there is no mutually supported protocol. If NextProtos is empty
// or the peer doesn't support ALPN, the connection will succeed and
// ConnectionState.NegotiatedProtocol will be empty.
NextProtos []string
// ServerName is used to verify the hostname on the returned
// certificates unless InsecureSkipVerify is given. It is also included
// in the client's handshake to support virtual hosting unless it is
// an IP address.
ServerName string
// ClientAuth determines the server's policy for
// TLS Client Authentication. The default is NoClientCert.
ClientAuth ClientAuthType
// ClientCAs defines the set of root certificate authorities
// that servers use if required to verify a client certificate
// by the policy in ClientAuth.
ClientCAs *x509.CertPool
// InsecureSkipVerify controls whether a client verifies the server's
// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
// accepts any certificate presented by the server and any host name in that
// certificate. In this mode, TLS is susceptible to machine-in-the-middle
// attacks unless custom verification is used. This should be used only for
// testing or in combination with VerifyConnection or VerifyPeerCertificate.
InsecureSkipVerify bool
// CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
// the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
//
// If CipherSuites is nil, a safe default list is used. The default cipher
// suites might change over time.
CipherSuites []uint16
// PreferServerCipherSuites is a legacy field and has no effect.
//
// It used to control whether the server would follow the client's or the
// server's preference. Servers now select the best mutually supported
// cipher suite based on logic that takes into account inferred client
// hardware, server hardware, and security.
//
// Deprecated: PreferServerCipherSuites is ignored.
PreferServerCipherSuites bool
// SessionTicketsDisabled may be set to true to disable session ticket and
// PSK (resumption) support. Note that on clients, session ticket support is
// also disabled if ClientSessionCache is nil.
SessionTicketsDisabled bool
// SessionTicketKey is used by TLS servers to provide session resumption.
// See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
// with random data before the first server handshake.
//
// Deprecated: if this field is left at zero, session ticket keys will be
// automatically rotated every day and dropped after seven days. For
// customizing the rotation schedule or synchronizing servers that are
// terminating connections for the same host, use SetSessionTicketKeys.
SessionTicketKey [32]byte
// ClientSessionCache is a cache of ClientSessionState entries for TLS
// session resumption. It is only used by clients.
ClientSessionCache ClientSessionCache
// MinVersion contains the minimum TLS version that is acceptable.
//
// By default, TLS 1.2 is currently used as the minimum when acting as a
// client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
// supported by this package, both as a client and as a server.
//
// The client-side default can temporarily be reverted to TLS 1.0 by
// including the value "x509sha1=1" in the GODEBUG environment variable.
// Note that this option will be removed in Go 1.19 (but it will still be
// possible to set this field to VersionTLS10 explicitly).
MinVersion uint16
// MaxVersion contains the maximum TLS version that is acceptable.
//
// By default, the maximum version supported by this package is used,
// which is currently TLS 1.3.
MaxVersion uint16
// CurvePreferences contains the elliptic curves that will be used in
// an ECDHE handshake, in preference order. If empty, the default will
// be used. The client will use the first preference as the type for
// its key share in TLS 1.3. This may change in the future.
CurvePreferences []CurveID
// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
// When true, the largest possible TLS record size is always used. When
// false, the size of TLS records may be adjusted in an attempt to
// improve latency.
DynamicRecordSizingDisabled bool
// Renegotiation controls what types of renegotiation are supported.
// The default, none, is correct for the vast majority of applications.
Renegotiation RenegotiationSupport
// KeyLogWriter optionally specifies a destination for TLS master secrets
// in NSS key log format that can be used to allow external programs
// such as Wireshark to decrypt TLS connections.
// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
// Use of KeyLogWriter compromises security and should only be
// used for debugging.
KeyLogWriter io.Writer
// contains filtered or unexported fields
}
A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified. A Config may be reused; the tls package will also not modify it.
func (*Config)BuildNameToCertificateDEPRECATED
(*Config) Clone ¶added in go1.8
func (c *Config) Clone() *Config
Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is being used concurrently by a TLS client or server.
(*Config) SetSessionTicketKeys ¶added in go1.5
func (c *Config) SetSessionTicketKeys(keys [][32]byte)
SetSessionTicketKeys updates the session ticket keys for a server.
The first key will be used when creating new tickets, while all keys can be used for decrypting tickets. It is safe to call this function while the server is running in order to rotate the session ticket keys. The function will panic if keys is empty.
Calling this function will turn off automatic session ticket key rotation.
If multiple servers are terminating connections for the same host they should all have the same session ticket keys. If the session ticket keys leaks, previously recorded and future TLS connections using those keys might be compromised.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
A Conn represents a secured connection. It implements the net.Conn interface.
func Client ¶
func Client(conn net.Conn, config *Config) *Conn
Client returns a new TLS client side connection using conn as the underlying transport. The config cannot be nil: users must set either ServerName or InsecureSkipVerify in the config.
func Dial ¶
func Dial(network, addr string, config *Config) (*Conn, error)
Dial connects to the given network address using net.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Dial interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.
func DialWithDialer ¶added in go1.3
func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error)
DialWithDialer connects to the given network address using dialer.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Any timeout or deadline given in the dialer apply to connection and TLS handshake as a whole.
DialWithDialer interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.
DialWithDialer uses context.Background internally; to specify the context, use Dialer.DialContext with NetDialer set to the desired dialer.
func Server ¶
func Server(conn net.Conn, config *Config) *Conn
Server returns a new TLS server side connection using conn as the underlying transport. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.
(*Conn) Close ¶
func (c *Conn) Close() error
Close closes the connection.
(*Conn) CloseWrite ¶added in go1.8
func (c *Conn) CloseWrite() error
CloseWrite shuts down the writing side of the connection. It should only be called once the handshake has completed and does not call CloseWrite on the underlying connection. Most callers should just use Close.
(*Conn) ConnectionState ¶
func (c *Conn) ConnectionState() ConnectionState
ConnectionState returns basic TLS details about the connection.
(*Conn) Handshake ¶
func (c *Conn) Handshake() error
Handshake runs the client or server handshake protocol if it has not yet been run.
Most uses of this package need not call Handshake explicitly: the first Read or Write will call it automatically.
For control over canceling or setting a timeout on a handshake, use HandshakeContext or the Dialer’s DialContext method instead.
(*Conn) HandshakeContext ¶added in go1.17
func (c *Conn) HandshakeContext(ctx context.Context) error
HandshakeContext runs the client or server handshake protocol if it has not yet been run.
The provided Context must be non-nil. If the context is canceled before the handshake is complete, the handshake is interrupted and an error is returned. Once the handshake has completed, cancellation of the context will not affect the connection.
Most uses of this package need not call HandshakeContext explicitly: the first Read or Write will call it automatically.
(*Conn) LocalAddr ¶
func (c *Conn) LocalAddr() net.Addr
LocalAddr returns the local network address.
(*Conn) NetConn ¶added in go1.18
func (c *Conn) NetConn() net.Conn
NetConn returns the underlying connection that is wrapped by c. Note that writing to or reading from this connection directly will corrupt the TLS session.
(*Conn) OCSPResponse ¶
func (c *Conn) OCSPResponse() []byte
OCSPResponse returns the stapled OCSP response from the TLS server, if any. (Only valid for client connections.)
(*Conn) Read ¶
func (c *Conn) Read(b []byte) (int, error)
Read reads data from the connection.
As Read calls Handshake, in order to prevent indefinite blocking a deadline must be set for both Read and Write before Read is called when the handshake has not yet completed. See SetDeadline, SetReadDeadline, and SetWriteDeadline.
(*Conn) RemoteAddr ¶
func (c *Conn) RemoteAddr() net.Addr
RemoteAddr returns the remote network address.
(*Conn) SetDeadline ¶
func (c *Conn) SetDeadline(t time.Time) error
SetDeadline sets the read and write deadlines associated with the connection. A zero value for t means Read and Write will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
(*Conn) SetReadDeadline ¶
func (c *Conn) SetReadDeadline(t time.Time) error
SetReadDeadline sets the read deadline on the underlying connection. A zero value for t means Read will not time out.
(*Conn) SetWriteDeadline ¶
func (c *Conn) SetWriteDeadline(t time.Time) error
SetWriteDeadline sets the write deadline on the underlying connection. A zero value for t means Write will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
(*Conn) VerifyHostname ¶
func (c *Conn) VerifyHostname(host string) error
VerifyHostname checks that the peer certificate chain is valid for connecting to host. If so, it returns nil; if not, it returns an error describing the problem.
(*Conn) Write ¶
func (c *Conn) Write(b []byte) (int, error)
Write writes data to the connection.
As Write calls Handshake, in order to prevent indefinite blocking a deadline must be set for both Read and Write before Write is called when the handshake has not yet completed. See SetDeadline, SetReadDeadline, and SetWriteDeadline.
type ConnectionState ¶
type ConnectionState struct {
// Version is the TLS version used by the connection (e.g. VersionTLS12).
Version uint16
// HandshakeComplete is true if the handshake has concluded.
HandshakeComplete bool
// DidResume is true if this connection was successfully resumed from a
// previous session with a session ticket or similar mechanism.
DidResume bool
// CipherSuite is the cipher suite negotiated for the connection (e.g.
// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
CipherSuite uint16
// NegotiatedProtocol is the application protocol negotiated with ALPN.
NegotiatedProtocol string
// NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
//
// Deprecated: this value is always true.
NegotiatedProtocolIsMutual bool
// ServerName is the value of the Server Name Indication extension sent by
// the client. It's available both on the server and on the client side.
ServerName string
// PeerCertificates are the parsed certificates sent by the peer, in the
// order in which they were sent. The first element is the leaf certificate
// that the connection is verified against.
//
// On the client side, it can't be empty. On the server side, it can be
// empty if Config.ClientAuth is not RequireAnyClientCert or
// RequireAndVerifyClientCert.
//
// PeerCertificates and its contents should not be modified.
PeerCertificates []*x509.Certificate
// VerifiedChains is a list of one or more chains where the first element is
// PeerCertificates[0] and the last element is from Config.RootCAs (on the
// client side) or Config.ClientCAs (on the server side).
//
// On the client side, it's set if Config.InsecureSkipVerify is false. On
// the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
// (and the peer provided a certificate) or RequireAndVerifyClientCert.
//
// VerifiedChains and its contents should not be modified.
VerifiedChains [][]*x509.Certificate
// SignedCertificateTimestamps is a list of SCTs provided by the peer
// through the TLS handshake for the leaf certificate, if any.
SignedCertificateTimestamps [][]byte
// OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
// response provided by the peer for the leaf certificate, if any.
OCSPResponse []byte
// TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
// Section 3). This value will be nil for TLS 1.3 connections and for all
// resumed connections.
//
// Deprecated: there are conditions in which this value might not be unique
// to a connection. See the Security Considerations sections of RFC 5705 and
// RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
TLSUnique []byte
// contains filtered or unexported fields
}
ConnectionState records basic TLS details about the connection.
(*ConnectionState) ExportKeyingMaterial ¶added in go1.11
func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)
ExportKeyingMaterial returns length bytes of exported key material in a new slice as defined in RFC 5705. If context is nil, it is not used as part of the seed. If the connection was set to allow renegotiation via Config.Renegotiation, this function will return an error.
type CurveID ¶added in go1.3
type CurveID uint16
CurveID is the type of a TLS identifier for an elliptic curve. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
In TLS 1.3, this type is called NamedGroup, but at this time this library only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
const (
CurveP256 CurveID = 23
CurveP384 CurveID = 24
CurveP521 CurveID = 25
X25519 CurveID = 29
)
(CurveID) String ¶added in go1.15
func (i CurveID) String() string
type Dialer ¶added in go1.15
type Dialer struct {
// NetDialer is the optional dialer to use for the TLS connections'
// underlying TCP connections.
// A nil NetDialer is equivalent to the net.Dialer zero value.
NetDialer *net.Dialer
// Config is the TLS configuration to use for new connections.
// A nil configuration is equivalent to the zero
// configuration; see the documentation of Config for the
// defaults.
Config *Config
}
Dialer dials TLS connections given a configuration and a Dialer for the underlying connection.
(*Dialer) Dial ¶added in go1.15
func (d *Dialer) Dial(network, addr string) (net.Conn, error)
Dial connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection.
The returned Conn, if any, will always be of type *Conn.
Dial uses context.Background internally; to specify the context, use DialContext.
(*Dialer) DialContext ¶added in go1.15
func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)
DialContext connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection.
The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Once successfully connected, any expiration of the context will not affect the connection.
The returned Conn, if any, will always be of type *Conn.
type RecordHeaderError ¶added in go1.6
type RecordHeaderError struct {
// Msg contains a human readable string that describes the error.
Msg string
// RecordHeader contains the five bytes of TLS record header that
// triggered the error.
RecordHeader [5]byte
// Conn provides the underlying net.Conn in the case that a client
// sent an initial handshake that didn't look like TLS.
// It is nil if there's already been a handshake or a TLS alert has
// been written to the connection.
Conn net.Conn
}
RecordHeaderError is returned when a TLS record header is invalid.
(RecordHeaderError) Error ¶added in go1.6
func (e RecordHeaderError) Error() string
type RenegotiationSupport ¶added in go1.7
type RenegotiationSupport int
RenegotiationSupport enumerates the different levels of support for TLS renegotiation. TLS renegotiation is the act of performing subsequent handshakes on a connection after the first. This significantly complicates the state machine and has been the source of numerous, subtle security issues. Initiating a renegotiation is not supported, but support for accepting renegotiation requests may be enabled.
Even when enabled, the server may not change its identity between handshakes (i.e. the leaf certificate must be the same). Additionally, concurrent handshake and application data flow is not permitted so renegotiation can only be used with protocols that synchronise with the renegotiation, such as HTTPS.
Renegotiation is not defined in TLS 1.3.
const (
// RenegotiateNever disables renegotiation.
RenegotiateNever RenegotiationSupport = iota
// RenegotiateOnceAsClient allows a remote server to request
// renegotiation once per connection.
RenegotiateOnceAsClient
// RenegotiateFreelyAsClient allows a remote server to repeatedly
// request renegotiation.
RenegotiateFreelyAsClient
)
type SignatureScheme ¶added in go1.8
type SignatureScheme uint16
SignatureScheme identifies a signature algorithm supported by TLS. See RFC 8446, Section 4.2.3.
const (
// RSASSA-PKCS1-v1_5 algorithms.
PKCS1WithSHA256 SignatureScheme = 0x0401
PKCS1WithSHA384 SignatureScheme = 0x0501
PKCS1WithSHA512 SignatureScheme = 0x0601
// RSASSA-PSS algorithms with public key OID rsaEncryption.
PSSWithSHA256 SignatureScheme = 0x0804
PSSWithSHA384 SignatureScheme = 0x0805
PSSWithSHA512 SignatureScheme = 0x0806
// ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
// EdDSA algorithms.
Ed25519 SignatureScheme = 0x0807
// Legacy signature and hash algorithms for TLS 1.2.
PKCS1WithSHA1 SignatureScheme = 0x0201
ECDSAWithSHA1 SignatureScheme = 0x0203
)
(SignatureScheme) String ¶added in go1.15
func (i SignatureScheme) String() string
Notes
Bugs
- The crypto/tls package only implements some countermeasures against Lucky13 attacks on CBC-mode encryption, and only on SHA1 variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
4.20 - x509
x509
https://pkg.go.dev/crypto/x509@go1.20.1
Package x509 implements a subset of the X.509 standard.
It allows parsing and generating certificates, certificate signing requests, certificate revocation lists, and encoded public and private keys. It provides a certificate verifier, complete with a chain builder.
The package targets the X.509 technical profile defined by the IETF (RFC 2459/3280/5280), and as further restricted by the CA/Browser Forum Baseline Requirements. There is minimal support for features outside of these profiles, as the primary goal of the package is to provide compatibility with the publicly trusted TLS certificate ecosystem and its policies and constraints.
On macOS and Windows, certificate verification is handled by system APIs, but the package aims to apply consistent validation rules across operating systems.
常量 ¶
This section is empty.
变量
var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
ErrUnsupportedAlgorithm results from attempting to perform an operation that involves algorithms that are not currently implemented.
var IncorrectPasswordError = errors.New("x509: decryption password incorrect")
IncorrectPasswordError is returned when an incorrect password is detected.
函数
func CreateCertificate ¶
func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error)
CreateCertificate creates a new X.509 v3 certificate based on a template. The following members of template are currently used:
- AuthorityKeyId
- BasicConstraintsValid
- CRLDistributionPoints
- DNSNames
- EmailAddresses
- ExcludedDNSDomains
- ExcludedEmailAddresses
- ExcludedIPRanges
- ExcludedURIDomains
- ExtKeyUsage
- ExtraExtensions
- IPAddresses
- IsCA
- IssuingCertificateURL
- KeyUsage
- MaxPathLen
- MaxPathLenZero
- NotAfter
- NotBefore
- OCSPServer
- PermittedDNSDomains
- PermittedDNSDomainsCritical
- PermittedEmailAddresses
- PermittedIPRanges
- PermittedURIDomains
- PolicyIdentifiers
- SerialNumber
- SignatureAlgorithm
- Subject
- SubjectKeyId
- URIs
- UnknownExtKeyUsage
The certificate is signed by parent. If parent is equal to template then the certificate is self-signed. The parameter pub is the public key of the certificate to be generated and priv is the private key of the signer.
The returned slice is the certificate in DER encoding.
The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and ed25519.PublicKey. pub must be a supported key type, and priv must be a crypto.Signer with a supported public key.
The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any, unless the resulting certificate is self-signed. Otherwise the value from template will be used.
If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId will be generated from the hash of the public key.
func CreateCertificateRequest ¶added in go1.3
func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)
CreateCertificateRequest creates a new certificate request based on a template. The following members of template are used:
- SignatureAlgorithm
- Subject
- DNSNames
- EmailAddresses
- IPAddresses
- URIs
- ExtraExtensions
- Attributes (deprecated)
priv is the private key to sign the CSR with, and the corresponding public key will be included in the CSR. It must implement crypto.Signer and its Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or ed25519.PrivateKey satisfies this.)
The returned slice is the certificate request in DER encoding.
func CreateRevocationList ¶added in go1.15
func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)
CreateRevocationList creates a new X.509 v2 Certificate Revocation List, according to RFC 5280, based on template.
The CRL is signed by priv which should be the private key associated with the public key in the issuer certificate.
The issuer may not be nil, and the crlSign bit must be set in KeyUsage in order to use it as a CRL issuer.
The issuer distinguished name CRL field and authority key identifier extension are populated using the issuer certificate. issuer must have SubjectKeyId set.
funcDecryptPEMBlockDEPRECATEDadded in go1.1
funcEncryptPEMBlockDEPRECATEDadded in go1.1
funcIsEncryptedPEMBlockDEPRECATEDadded in go1.1
func MarshalECPrivateKey ¶added in go1.2
func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)
MarshalECPrivateKey converts an EC private key to SEC 1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type “EC PRIVATE KEY”. For a more flexible key format which is not EC specific, use MarshalPKCS8PrivateKey.
func MarshalPKCS1PrivateKey ¶
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
MarshalPKCS1PrivateKey converts an RSA private key to PKCS #1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type “RSA PRIVATE KEY”. For a more flexible key format which is not RSA specific, use MarshalPKCS8PrivateKey.
func MarshalPKCS1PublicKey ¶added in go1.10
func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte
MarshalPKCS1PublicKey converts an RSA public key to PKCS #1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type “RSA PUBLIC KEY”.
func MarshalPKCS8PrivateKey ¶added in go1.10
func MarshalPKCS8PrivateKey(key any) ([]byte, error)
MarshalPKCS8PrivateKey converts a private key to PKCS #8, ASN.1 DER form.
The following key types are currently supported: *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey (not a pointer), and *ecdh.PrivateKey. Unsupported key types result in an error.
This kind of key is commonly encoded in PEM blocks of type “PRIVATE KEY”.
func MarshalPKIXPublicKey ¶
func MarshalPKIXPublicKey(pub any) ([]byte, error)
MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form. The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).
The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey (not a pointer), and *ecdh.PublicKey. Unsupported key types result in an error.
This kind of key is commonly encoded in PEM blocks of type “PUBLIC KEY”.
funcParseCRLDEPRECATED
funcParseDERCRLDEPRECATED
func ParseECPrivateKey ¶added in go1.1
func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)
ParseECPrivateKey parses an EC private key in SEC 1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type “EC PRIVATE KEY”.
func ParsePKCS1PrivateKey ¶
func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
ParsePKCS1PrivateKey parses an RSA private key in PKCS #1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type “RSA PRIVATE KEY”.
func ParsePKCS1PublicKey ¶added in go1.10
func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error)
ParsePKCS1PublicKey parses an RSA public key in PKCS #1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type “RSA PUBLIC KEY”.
func ParsePKCS8PrivateKey ¶
func ParsePKCS8PrivateKey(der []byte) (key any, err error)
ParsePKCS8PrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER form.
It returns a *rsa.PrivateKey, a *ecdsa.PrivateKey, a ed25519.PrivateKey (not a pointer), or a *ecdh.PublicKey (for X25519). More types might be supported in the future.
This kind of key is commonly encoded in PEM blocks of type “PRIVATE KEY”.
func ParsePKIXPublicKey ¶
func ParsePKIXPublicKey(derBytes []byte) (pub any, err error)
ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).
It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey (not a pointer), or *ecdh.PublicKey (for X25519). More types might be supported in the future.
This kind of key is commonly encoded in PEM blocks of type “PUBLIC KEY”.
func SetFallbackRoots ¶added in go1.20
func SetFallbackRoots(roots *CertPool)
SetFallbackRoots sets the roots to use during certificate verification, if no custom roots are specified and a platform verifier or a system certificate pool is not available (for instance in a container which does not have a root certificate bundle). SetFallbackRoots will panic if roots is nil.
SetFallbackRoots may only be called once, if called multiple times it will panic.
The fallback behavior can be forced on all platforms, even when there is a system certificate pool, by setting GODEBUG=x509usefallbackroots=1 (note that on Windows and macOS this will disable usage of the platform verification APIs and cause the pure Go verifier to be used). Setting x509usefallbackroots=1 without calling SetFallbackRoots has no effect.
类型
type CertPool ¶
type CertPool struct {
// contains filtered or unexported fields
}
CertPool is a set of certificates.
func NewCertPool ¶
func NewCertPool() *CertPool
NewCertPool returns a new, empty CertPool.
func SystemCertPool ¶added in go1.7
func SystemCertPool() (*CertPool, error)
SystemCertPool returns a copy of the system cert pool.
On Unix systems other than macOS the environment variables SSL_CERT_FILE and SSL_CERT_DIR can be used to override the system default locations for the SSL certificate file and SSL certificate files directory, respectively. The latter can be a colon-separated list.
Any mutations to the returned pool are not written to disk and do not affect any other pool returned by SystemCertPool.
New changes in the system cert pool might not be reflected in subsequent calls.
(*CertPool) AddCert ¶
func (s *CertPool) AddCert(cert *Certificate)
AddCert adds a certificate to a pool.
(*CertPool) AppendCertsFromPEM ¶
func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)
AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. It appends any certificates found to s and reports whether any certificates were successfully parsed.
On many Linux systems, /etc/ssl/cert.pem will contain the system wide set of root CAs in a format suitable for this function.
(*CertPool) Clone ¶added in go1.19
func (s *CertPool) Clone() *CertPool
Clone returns a copy of s.
(*CertPool) Equal ¶added in go1.19
func (s *CertPool) Equal(other *CertPool) bool
Equal reports whether s and other are equal.
func (*CertPool)SubjectsDEPRECATED
type Certificate ¶
type Certificate struct {
Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
RawSubject []byte // DER encoded Subject
RawIssuer []byte // DER encoded Issuer
Signature []byte
SignatureAlgorithm SignatureAlgorithm
PublicKeyAlgorithm PublicKeyAlgorithm
PublicKey any
Version int
SerialNumber *big.Int
Issuer pkix.Name
Subject pkix.Name
NotBefore, NotAfter time.Time // Validity bounds.
KeyUsage KeyUsage
// Extensions contains raw X.509 extensions. When parsing certificates,
// this can be used to extract non-critical extensions that are not
// parsed by this package. When marshaling certificates, the Extensions
// field is ignored, see ExtraExtensions.
Extensions []pkix.Extension
// ExtraExtensions contains extensions to be copied, raw, into any
// marshaled certificates. Values override any extensions that would
// otherwise be produced based on the other fields. The ExtraExtensions
// field is not populated when parsing certificates, see Extensions.
ExtraExtensions []pkix.Extension
// UnhandledCriticalExtensions contains a list of extension IDs that
// were not (fully) processed when parsing. Verify will fail if this
// slice is non-empty, unless verification is delegated to an OS
// library which understands all the critical extensions.
//
// Users can access these extensions using Extensions and can remove
// elements from this slice if they believe that they have been
// handled.
UnhandledCriticalExtensions []asn1.ObjectIdentifier
ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
// BasicConstraintsValid indicates whether IsCA, MaxPathLen,
// and MaxPathLenZero are valid.
BasicConstraintsValid bool
IsCA bool
// MaxPathLen and MaxPathLenZero indicate the presence and
// value of the BasicConstraints' "pathLenConstraint".
//
// When parsing a certificate, a positive non-zero MaxPathLen
// means that the field was specified, -1 means it was unset,
// and MaxPathLenZero being true mean that the field was
// explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
// should be treated equivalent to -1 (unset).
//
// When generating a certificate, an unset pathLenConstraint
// can be requested with either MaxPathLen == -1 or using the
// zero value for both MaxPathLen and MaxPathLenZero.
MaxPathLen int
// MaxPathLenZero indicates that BasicConstraintsValid==true
// and MaxPathLen==0 should be interpreted as an actual
// maximum path length of zero. Otherwise, that combination is
// interpreted as MaxPathLen not being set.
MaxPathLenZero bool
SubjectKeyId []byte
AuthorityKeyId []byte
// RFC 5280, 4.2.2.1 (Authority Information Access)
OCSPServer []string
IssuingCertificateURL []string
// Subject Alternate Name values. (Note that these values may not be valid
// if invalid values were contained within a parsed certificate. For
// example, an element of DNSNames may not be a valid DNS domain name.)
DNSNames []string
EmailAddresses []string
IPAddresses []net.IP
URIs []*url.URL
// Name constraints
PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
PermittedDNSDomains []string
ExcludedDNSDomains []string
PermittedIPRanges []*net.IPNet
ExcludedIPRanges []*net.IPNet
PermittedEmailAddresses []string
ExcludedEmailAddresses []string
PermittedURIDomains []string
ExcludedURIDomains []string
// CRL Distribution Points
CRLDistributionPoints []string
PolicyIdentifiers []asn1.ObjectIdentifier
}
A Certificate represents an X.509 certificate.
func ParseCertificate ¶
func ParseCertificate(der []byte) (*Certificate, error)
ParseCertificate parses a single certificate from the given ASN.1 DER data.
func ParseCertificates ¶
func ParseCertificates(der []byte) ([]*Certificate, error)
ParseCertificates parses one or more certificates from the given ASN.1 DER data. The certificates must be concatenated with no intermediate padding.
func (*Certificate)CheckCRLSignatureDEPRECATED
(*Certificate) CheckSignature ¶
func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error
CheckSignature verifies that signature is a valid signature over signed from c’s public key.
This is a low-level API that performs no validity checks on the certificate.
MD5WithRSA signatures are rejected, while SHA1WithRSA and ECDSAWithSHA1 signatures are currently accepted.
(*Certificate) CheckSignatureFrom ¶
func (c *Certificate) CheckSignatureFrom(parent *Certificate) error
CheckSignatureFrom verifies that the signature on c is a valid signature from parent.
This is a low-level API that performs very limited checks, and not a full path verifier. Most users should use Certificate.Verify instead.
func (*Certificate)CreateCRLDEPRECATED
(*Certificate) Equal ¶
func (c *Certificate) Equal(other *Certificate) bool
(*Certificate) Verify ¶
func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
Verify attempts to verify c by building one or more chains from c to a certificate in opts.Roots, using certificates in opts.Intermediates if needed. If successful, it returns one or more chains where the first element of the chain is c and the last element is from opts.Roots.
If opts.Roots is nil, the platform verifier might be used, and verification details might differ from what is described below. If system roots are unavailable the returned error will be of type SystemRootsError.
Name constraints in the intermediates will be applied to all names claimed in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim example.com if an intermediate doesn’t permit it, even if example.com is not the name being validated. Note that DirectoryName constraints are not supported.
Name constraint validation follows the rules from RFC 5280, with the addition that DNS name constraints may use the leading period format defined for emails and URIs. When a constraint has a leading period it indicates that at least one additional label must be prepended to the constrained name to be considered valid.
Extended Key Usage values are enforced nested down a chain, so an intermediate or root that enumerates EKUs prevents a leaf from asserting an EKU not in that list. (While this is not specified, it is common practice in order to limit the types of certificates a CA can issue.)
Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported, and will not be used to build chains.
Certificates other than c in the returned chains should not be modified.
WARNING: this function doesn’t do any revocation checking.
(*Certificate) VerifyHostname ¶
func (c *Certificate) VerifyHostname(h string) error
VerifyHostname returns nil if c is a valid certificate for the named host. Otherwise it returns an error describing the mismatch.
IP addresses can be optionally enclosed in square brackets and are checked against the IPAddresses field. Other names are checked case insensitively against the DNSNames field. If the names are valid hostnames, the certificate fields can have a wildcard as the left-most label.
Note that the legacy Common Name field is ignored.
type CertificateInvalidError ¶
type CertificateInvalidError struct {
Cert *Certificate
Reason InvalidReason
Detail string
}
CertificateInvalidError results when an odd error occurs. Users of this library probably want to handle all these errors uniformly.
(CertificateInvalidError) Error ¶
func (e CertificateInvalidError) Error() string
type CertificateRequest ¶added in go1.3
type CertificateRequest struct {
Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
RawSubject []byte // DER encoded Subject.
Version int
Signature []byte
SignatureAlgorithm SignatureAlgorithm
PublicKeyAlgorithm PublicKeyAlgorithm
PublicKey any
Subject pkix.Name
// Attributes contains the CSR attributes that can parse as
// pkix.AttributeTypeAndValueSET.
//
// Deprecated: Use Extensions and ExtraExtensions instead for parsing and
// generating the requestedExtensions attribute.
Attributes []pkix.AttributeTypeAndValueSET
// Extensions contains all requested extensions, in raw form. When parsing
// CSRs, this can be used to extract extensions that are not parsed by this
// package.
Extensions []pkix.Extension
// ExtraExtensions contains extensions to be copied, raw, into any CSR
// marshaled by CreateCertificateRequest. Values override any extensions
// that would otherwise be produced based on the other fields but are
// overridden by any extensions specified in Attributes.
//
// The ExtraExtensions field is not populated by ParseCertificateRequest,
// see Extensions instead.
ExtraExtensions []pkix.Extension
// Subject Alternate Name values.
DNSNames []string
EmailAddresses []string
IPAddresses []net.IP
URIs []*url.URL
}
CertificateRequest represents a PKCS #10, certificate signature request.
func ParseCertificateRequest ¶added in go1.3
func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
ParseCertificateRequest parses a single certificate request from the given ASN.1 DER data.
(*CertificateRequest) CheckSignature ¶added in go1.5
func (c *CertificateRequest) CheckSignature() error
CheckSignature reports whether the signature on c is valid.
type ConstraintViolationError ¶
type ConstraintViolationError struct{}
ConstraintViolationError results when a requested usage is not permitted by a certificate. For example: checking a signature when the public key isn’t a certificate signing key.
(ConstraintViolationError) Error ¶
func (ConstraintViolationError) Error() string
type ExtKeyUsage ¶
type ExtKeyUsage int
ExtKeyUsage represents an extended set of actions that are valid for a given key. Each of the ExtKeyUsage* constants define a unique action.
const (
ExtKeyUsageAny ExtKeyUsage = iota
ExtKeyUsageServerAuth
ExtKeyUsageClientAuth
ExtKeyUsageCodeSigning
ExtKeyUsageEmailProtection
ExtKeyUsageIPSECEndSystem
ExtKeyUsageIPSECTunnel
ExtKeyUsageIPSECUser
ExtKeyUsageTimeStamping
ExtKeyUsageOCSPSigning
ExtKeyUsageMicrosoftServerGatedCrypto
ExtKeyUsageNetscapeServerGatedCrypto
ExtKeyUsageMicrosoftCommercialCodeSigning
ExtKeyUsageMicrosoftKernelCodeSigning
)
type HostnameError ¶
type HostnameError struct {
Certificate *Certificate
Host string
}
HostnameError results when the set of authorized names doesn’t match the requested name.
(HostnameError) Error ¶
func (h HostnameError) Error() string
type InsecureAlgorithmError ¶added in go1.6
type InsecureAlgorithmError SignatureAlgorithm
An InsecureAlgorithmError indicates that the SignatureAlgorithm used to generate the signature is not secure, and the signature has been rejected.
To temporarily restore support for SHA-1 signatures, include the value “x509sha1=1” in the GODEBUG environment variable. Note that this option will be removed in a future release.
(InsecureAlgorithmError) Error ¶added in go1.6
func (e InsecureAlgorithmError) Error() string
type InvalidReason ¶
type InvalidReason int
const (
// NotAuthorizedToSign results when a certificate is signed by another
// which isn't marked as a CA certificate.
NotAuthorizedToSign InvalidReason = iota
// Expired results when a certificate has expired, based on the time
// given in the VerifyOptions.
Expired
// CANotAuthorizedForThisName results when an intermediate or root
// certificate has a name constraint which doesn't permit a DNS or
// other name (including IP address) in the leaf certificate.
CANotAuthorizedForThisName
// TooManyIntermediates results when a path length constraint is
// violated.
TooManyIntermediates
// IncompatibleUsage results when the certificate's key usage indicates
// that it may only be used for a different purpose.
IncompatibleUsage
// NameMismatch results when the subject name of a parent certificate
// does not match the issuer name in the child.
NameMismatch
// NameConstraintsWithoutSANs is a legacy error and is no longer returned.
NameConstraintsWithoutSANs
// UnconstrainedName results when a CA certificate contains permitted
// name constraints, but leaf certificate contains a name of an
// unsupported or unconstrained type.
UnconstrainedName
// TooManyConstraints results when the number of comparison operations
// needed to check a certificate exceeds the limit set by
// VerifyOptions.MaxConstraintComparisions. This limit exists to
// prevent pathological certificates can consuming excessive amounts of
// CPU time to verify.
TooManyConstraints
// CANotAuthorizedForExtKeyUsage results when an intermediate or root
// certificate does not permit a requested extended key usage.
CANotAuthorizedForExtKeyUsage
)
type KeyUsage ¶
type KeyUsage int
KeyUsage represents the set of actions that are valid for a given key. It’s a bitmap of the KeyUsage* constants.
const (
KeyUsageDigitalSignature KeyUsage = 1 << iota
KeyUsageContentCommitment
KeyUsageKeyEncipherment
KeyUsageDataEncipherment
KeyUsageKeyAgreement
KeyUsageCertSign
KeyUsageCRLSign
KeyUsageEncipherOnly
KeyUsageDecipherOnly
)
type PEMCipher ¶added in go1.1
type PEMCipher int
const (
PEMCipherDES PEMCipher
PEMCipher3DES
PEMCipherAES128
PEMCipherAES192
PEMCipherAES256
)
Possible values for the EncryptPEMBlock encryption algorithm.
type PublicKeyAlgorithm ¶
type PublicKeyAlgorithm int
const (
UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
RSA
DSA // Only supported for parsing.
ECDSA
Ed25519
)
(PublicKeyAlgorithm) String ¶added in go1.10
func (algo PublicKeyAlgorithm) String() string
type RevocationList ¶added in go1.15
type RevocationList struct {
// Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,
// signatureAlgorithm, and signatureValue.)
Raw []byte
// RawTBSRevocationList contains just the tbsCertList portion of the ASN.1
// DER.
RawTBSRevocationList []byte
// RawIssuer contains the DER encoded Issuer.
RawIssuer []byte
// Issuer contains the DN of the issuing certificate.
Issuer pkix.Name
// AuthorityKeyId is used to identify the public key associated with the
// issuing certificate. It is populated from the authorityKeyIdentifier
// extension when parsing a CRL. It is ignored when creating a CRL; the
// extension is populated from the issuing certificate itself.
AuthorityKeyId []byte
Signature []byte
// SignatureAlgorithm is used to determine the signature algorithm to be
// used when signing the CRL. If 0 the default algorithm for the signing
// key will be used.
SignatureAlgorithm SignatureAlgorithm
// RevokedCertificates is used to populate the revokedCertificates
// sequence in the CRL, it may be empty. RevokedCertificates may be nil,
// in which case an empty CRL will be created.
RevokedCertificates []pkix.RevokedCertificate
// Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
// which should be a monotonically increasing sequence number for a given
// CRL scope and CRL issuer. It is also populated from the cRLNumber
// extension when parsing a CRL.
Number *big.Int
// ThisUpdate is used to populate the thisUpdate field in the CRL, which
// indicates the issuance date of the CRL.
ThisUpdate time.Time
// NextUpdate is used to populate the nextUpdate field in the CRL, which
// indicates the date by which the next CRL will be issued. NextUpdate
// must be greater than ThisUpdate.
NextUpdate time.Time
// Extensions contains raw X.509 extensions. When creating a CRL,
// the Extensions field is ignored, see ExtraExtensions.
Extensions []pkix.Extension
// ExtraExtensions contains any additional extensions to add directly to
// the CRL.
ExtraExtensions []pkix.Extension
}
RevocationList contains the fields used to create an X.509 v2 Certificate Revocation list with CreateRevocationList.
func ParseRevocationList ¶added in go1.19
func ParseRevocationList(der []byte) (*RevocationList, error)
ParseRevocationList parses a X509 v2 Certificate Revocation List from the given ASN.1 DER data.
(*RevocationList) CheckSignatureFrom ¶added in go1.19
func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error
CheckSignatureFrom verifies that the signature on rl is a valid signature from issuer.
type SignatureAlgorithm ¶
type SignatureAlgorithm int
const (
UnknownSignatureAlgorithm SignatureAlgorithm = iota
MD2WithRSA // Unsupported.
MD5WithRSA // Only supported for signing, not verification.
SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
SHA256WithRSA
SHA384WithRSA
SHA512WithRSA
DSAWithSHA1 // Unsupported.
DSAWithSHA256 // Unsupported.
ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
ECDSAWithSHA256
ECDSAWithSHA384
ECDSAWithSHA512
SHA256WithRSAPSS
SHA384WithRSAPSS
SHA512WithRSAPSS
PureEd25519
)
(SignatureAlgorithm) String ¶added in go1.6
func (algo SignatureAlgorithm) String() string
type SystemRootsError ¶added in go1.1
type SystemRootsError struct {
Err error
}
SystemRootsError results when we fail to load the system root certificates.
(SystemRootsError) Error ¶added in go1.1
func (se SystemRootsError) Error() string
(SystemRootsError) Unwrap ¶added in go1.16
func (se SystemRootsError) Unwrap() error
type UnhandledCriticalExtension ¶
type UnhandledCriticalExtension struct{}
(UnhandledCriticalExtension) Error ¶
func (h UnhandledCriticalExtension) Error() string
type UnknownAuthorityError ¶
type UnknownAuthorityError struct {
Cert *Certificate
// contains filtered or unexported fields
}
UnknownAuthorityError results when the certificate issuer is unknown
(UnknownAuthorityError) Error ¶
func (e UnknownAuthorityError) Error() string
type VerifyOptions ¶
type VerifyOptions struct {
// DNSName, if set, is checked against the leaf certificate with
// Certificate.VerifyHostname or the platform verifier.
DNSName string
// Intermediates is an optional pool of certificates that are not trust
// anchors, but can be used to form a chain from the leaf certificate to a
// root certificate.
Intermediates *CertPool
// Roots is the set of trusted root certificates the leaf certificate needs
// to chain up to. If nil, the system roots or the platform verifier are used.
Roots *CertPool
// CurrentTime is used to check the validity of all certificates in the
// chain. If zero, the current time is used.
CurrentTime time.Time
// KeyUsages specifies which Extended Key Usage values are acceptable. A
// chain is accepted if it allows any of the listed values. An empty list
// means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
KeyUsages []ExtKeyUsage
// MaxConstraintComparisions is the maximum number of comparisons to
// perform when checking a given certificate's name constraints. If
// zero, a sensible default is used. This limit prevents pathological
// certificates from consuming excessive amounts of CPU time when
// validating. It does not apply to the platform verifier.
MaxConstraintComparisions int
}
VerifyOptions contains parameters for Certificate.Verify.
4.21 - x509/pkix
pkix
https://pkg.go.dev/crypto/x509/pkix@go1.20.1
Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
常量 ¶
This section is empty.
变量
This section is empty.
函数
This section is empty.
类型
type AlgorithmIdentifier ¶
type AlgorithmIdentifier struct {
Algorithm asn1.ObjectIdentifier
Parameters asn1.RawValue `asn1:"optional"`
}
AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC 5280, section 4.1.1.2.
type AttributeTypeAndValue ¶
type AttributeTypeAndValue struct {
Type asn1.ObjectIdentifier
Value any
}
AttributeTypeAndValue mirrors the ASN.1 structure of the same name in RFC 5280, Section 4.1.2.4.
type AttributeTypeAndValueSET ¶added in go1.3
type AttributeTypeAndValueSET struct {
Type asn1.ObjectIdentifier
Value [][]AttributeTypeAndValue `asn1:"set"`
}
AttributeTypeAndValueSET represents a set of ASN.1 sequences of AttributeTypeAndValue sequences from RFC 2986 (PKCS #10).
typeCertificateListDEPRECATED
type Extension ¶
type Extension struct {
Id asn1.ObjectIdentifier
Critical bool `asn1:"optional"`
Value []byte
}
Extension represents the ASN.1 structure of the same name. See RFC 5280, section 4.2.
type Name ¶
type Name struct {
Country, Organization, OrganizationalUnit []string
Locality, Province []string
StreetAddress, PostalCode []string
SerialNumber, CommonName string
// Names contains all parsed attributes. When parsing distinguished names,
// this can be used to extract non-standard attributes that are not parsed
// by this package. When marshaling to RDNSequences, the Names field is
// ignored, see ExtraNames.
Names []AttributeTypeAndValue
// ExtraNames contains attributes to be copied, raw, into any marshaled
// distinguished names. Values override any attributes with the same OID.
// The ExtraNames field is not populated when parsing, see Names.
ExtraNames []AttributeTypeAndValue
}
Name represents an X.509 distinguished name. This only includes the common elements of a DN. Note that Name is only an approximation of the X.509 structure. If an accurate representation is needed, asn1.Unmarshal the raw subject or issuer as an RDNSequence.
(*Name) FillFromRDNSequence ¶
func (n *Name) FillFromRDNSequence(rdns *RDNSequence)
FillFromRDNSequence populates n from the provided RDNSequence. Multi-entry RDNs are flattened, all entries are added to the relevant n fields, and the grouping is not preserved.
(Name) String ¶added in go1.10
func (n Name) String() string
String returns the string form of n, roughly following the RFC 2253 Distinguished Names syntax.
(Name) ToRDNSequence ¶
func (n Name) ToRDNSequence() (ret RDNSequence)
ToRDNSequence converts n into a single RDNSequence. The following attributes are encoded as multi-value RDNs:
- Country
- Organization
- OrganizationalUnit
- Locality
- Province
- StreetAddress
- PostalCode
Each ExtraNames entry is encoded as an individual RDN.
type RDNSequence ¶
type RDNSequence []RelativeDistinguishedNameSET
(RDNSequence) String ¶added in go1.10
func (r RDNSequence) String() string
String returns a string representation of the sequence r, roughly following the RFC 2253 Distinguished Names syntax.
type RelativeDistinguishedNameSET ¶
type RelativeDistinguishedNameSET []AttributeTypeAndValue
type RevokedCertificate ¶
type RevokedCertificate struct {
SerialNumber *big.Int
RevocationTime time.Time
Extensions []Extension `asn1:"optional"`
}
RevokedCertificate represents the ASN.1 structure of the same name. See RFC 5280, section 5.1.
5 - database
5.1 - sql
sql
https://pkg.go.dev/database/sql@go1.20.1
sql包提供了一个围绕SQL(或类SQL)数据库的通用接口。
sql包必须与数据库驱动程序一起使用。参见https://golang.org/s/sqldrivers,获取驱动程序的列表。
不支持上下文取消的驱动程序将等到查询完成后才会返回。
关于用法的例子,请参见wiki页面https://golang.org/s/sqlwiki。
Example (OpenDBCLI)
|
|
Example (OpenDBService)
|
|
常量
This section is empty.
变量
|
|
ErrConnDone 被任何在已经返回到连接池的连接上执行的操作返回。
|
|
ErrNoRows 在 Scan 时由 QueryRow 不返回行时返回。在这种情况下,QueryRow 返回一个占位符 *Row 值,直到扫描时才会出现此错误。
|
|
ErrTxDone 被任何在已经提交或回滚的事务上执行的操作返回。
函数
func Drivers <- go1.4
|
|
Drivers函数返回已注册驱动程序名称的排序列表。
func Register
|
|
Register函数使用提供的名称使数据库驱动程序可用。如果使用相同的名称两次调用Register或者驱动程序为nil,则会引发panic。
类型
type ColumnType <- go1.8
|
|
ColumnType结构体包含列的名称和类型。
(*ColumnType) DatabaseTypeName <- go1.8
|
|
DatabaseTypeName方法返回列类型的数据库系统名称。如果返回空字符串,则不支持驱动程序类型名称。请查阅您的驱动程序文档以获取驱动程序数据类型列表。不包括长度说明符。常见类型名称包括"VARCHAR",“TEXT”,“NVARCHAR”,“DECIMAL”,“BOOL”,“INT"和"BIGINT”。
(*ColumnType) DecimalSize <- go1.8
|
|
DecimalSize方法返回十进制类型的比例和精度。如果不适用或不受支持,则为假。
(*ColumnType) Length <- go1.8
|
|
Length方法返回变量长度列类型(如文本和二进制字段类型)的列类型长度。如果类型长度不受限制,则值将是math.MaxInt64(任何数据库限制仍将适用)。如果列类型不是可变长度,例如int,或者驱动程序不支持,则为false。
(*ColumnType) Name <- go1.8
|
|
Name方法返回列的名称或别名。
(*ColumnType) Nullable <- go1.8
|
|
Nullable方法报告列是否可以为null。如果驱动程序不支持此属性,则ok将为false。
(*ColumnType) ScanType <- go1.8
|
|
ScanType方法返回适合使用Rows.Scan进行扫描的Go类型。如果驱动程序不支持此属性,则ScanType将返回空接口的类型。
type Conn <- go1.9
|
|
Conn结构体表示一个单独的数据库连接,而不是数据库连接池。除非有特定需要一个连续的单个数据库连接,否则请优先使用 DB 来运行查询。
在调用 Close方法以将连接返回到数据库池之前,Conn 必须调用 Close方法,可能与正在运行的查询同时进行。
调用 Close方法后,连接上的所有操作都将失败,并返回 ErrConnDone。
(*Conn) BeginTx <- go1.9
|
|
BeginTx方法开始一个事务。
提供的上下文会一直使用到事务提交或回滚。如果上下文被取消,sql 包将回滚事务。如果传递给 BeginTx 的上下文被取消,Tx.Commit 将返回一个错误。
提供的 TxOptions 是可选的,如果应使用默认值,则可以为 nil。如果使用了非默认的隔离级别,并且该驱动程序不支持,将返回一个错误。
(*Conn) Close <- go1.9
|
|
Close方法将连接返回到连接池。Close方法后的所有操作都将返回 ErrConnDone。Close 方法可以与其他操作并发调用,它将阻塞,直到所有其他操作完成。在调用 Close 前,先取消任何使用的上下文,然后直接调用它可能会很有用。
(*Conn) ExecContext <- go1.9
|
|
ExecContext方法执行一条查询,而不返回任何行。args 用于查询中的任何占位符参数。
ExecContext Example
|
|
(*Conn) PingContext <- go1.9
|
|
PingContext方法验证与数据库的连接是否仍然存活。
(*Conn) PrepareContext <- go1.9
|
|
PrepareContext方法为以后的查询或执行创建一个准备好的语句。可以从返回的语句中并发运行多个查询或执行。调用者在不再需要语句时必须调用语句的 Close 方法。
提供的上下文用于准备语句,而不是执行语句的上下文。
(*Conn) QueryContext <- go1.9
|
|
QueryContext方法执行一个返回行的查询,通常是SELECT。args参数用于查询中的任何占位符参数。
(*Conn) QueryRowContext <- go1.9
|
|
QueryRowContext方法执行一个预期返回最多一行的查询。QueryRowContext总是返回一个非nil值。错误会被推迟到调用Row的Scan方法时返回。如果查询没有选择任何行,则* Row的Scan将返回ErrNoRows。否则,*Row的Scan扫描第一个选择的行并丢弃其余的行。
(*Conn) Raw <- go1.13
|
|
Raw方法执行f,暴露底层驱动程序连接。driverConn不能在f之外使用。
一旦f返回且err不是driver.ErrBadConn,Conn将继续可用,直到调用Conn.Close为止。
type DB
|
|
DB结构体是表示零个或多个底层连接池的数据库句柄。它可以被多个goroutine并发使用。
sql包会自动创建和释放连接;它还维护一个空闲连接的自由池。如果数据库有每个连接状态的概念,则可以在事务(Tx)或连接(Conn)中可靠地观察到此状态。一旦调用DB.Begin,返回的Tx将绑定到单个连接。一旦在事务上调用Commit或Rollback,该事务的连接就会返回到DB的空闲连接池中。池的大小可以使用SetMaxIdleConns进行控制。
func Open
|
|
Open函数通过其数据库驱动程序名称和驱动程序特定的数据源名称打开一个数据库,通常至少包含数据库名称和连接信息。
大多数用户将通过返回*DB的特定于驱动程序的连接助手函数打开数据库。Go标准库中不包含任何数据库驱动程序。请参阅https://golang.org/s/sqldrivers以获取第三方驱动程序的列表。
Open函数可能只验证其参数而不创建到数据库的连接。要验证数据源名称是否有效,请调用Ping。
返回的DB可安全地由多个goroutine并发使用,并维护其自己的空闲连接池。因此,应该只调用一次Open函数。很少需要关闭DB。
func OpenDB <- go1.10
|
|
OpenDB函数使用Connector打开数据库,允许驱动程序绕过基于字符串的数据源名称。
大多数用户将通过特定于驱动程序的连接助手函数打开数据库,该函数返回*DB。Go标准库中不包含任何数据库驱动程序。有关第三方驱动程序的列表,请参见https://golang.org/s/sqldrivers。
OpenDB函数可能只是验证其参数而没有创建到数据库的连接。要验证数据源名称是否有效,请调用Ping。
返回的DB安全地支持多个goroutine的并发使用,并维护其自己的空闲连接池。因此,OpenDB函数应该只调用一次。很少需要关闭DB。
(*DB) Begin
|
|
Begin方法开始一个事务。默认的隔离级别取决于驱动程序。
Begin方法在内部使用context.Background;要指定上下文,请使用BeginTx方法。
(*DB) BeginTx <- go1.8
|
|
BeginTx方法开始一个事务。
提供的上下文用于直到事务提交或回滚。如果上下文被取消,则sql包将回滚事务。如果提供给BeginTx方法的上下文被取消,Tx.Commit将返回错误。
提供的TxOptions是可选的,如果应使用默认值,则可以为nil。如果使用驱动程序不支持的非默认隔离级别,则会返回错误。
BeginTx Example
|
|
(*DB) Close
|
|
Close方法关闭数据库并防止启动新查询。然后,Close方法等待在服务器上已经开始处理的所有查询完成。
很少需要关闭DB,因为DB句柄应该是长期存在的并在许多goroutine之间共享。
(*DB) Conn <- go1.9
|
|
Conn方法通过打开一个新连接或从连接池中返回一个现有连接来返回单个连接。 Conn 将阻塞直到返回连接或取消 ctx。在同一 Conn 上运行的查询将在同一个数据库会话中运行。
每个 Conn方法必须通过调用 Conn.Close 返回到数据库池中。
(*DB) Driver
|
|
Driver方法返回数据库的底层驱动程序。
(*DB) Exec
|
|
Exec方法执行一个查询,而不返回任何行。 args 是查询中任何占位符参数的参数。
Exec方法内部使用 context.Background。要指定上下文,请使用 ExecContext方法。
(*DB) ExecContext <- go1.8
|
|
ExecContext方法执行一个查询,而不返回任何行。 args 是查询中任何占位符参数的参数。
ExecContext Example
|
|
(*DB) Ping <- go1.1
|
|
Ping方法验证与数据库的连接仍然存在,必要时建立连接。
Ping方法内部使用 context.Background。要指定上下文,请使用 PingContext方法。
(*DB) PingContext <- go1.8
|
|
PingContext方法验证与数据库的连接仍然存在,必要时建立连接。
PingContext Example
|
|
(*DB) Prepare
|
|
Prepare方法创建一个准备好的语句,以便以后进行查询或执行操作。可以从返回的语句中并发运行多个查询或执行。调用者在语句不再需要时必须调用语句的 Close 方法。
Prepare方法内部使用 context.Background。要指定上下文,请使用 PrepareContext方法。
Prepare Example
|
|
(*DB) PrepareContext <- go1.8
|
|
PrepareContext方法创建一个准备好的语句,以便以后进行查询或执行操作。可以从返回的语句中并发运行多个查询或执行。调用者在语句不再需要时必须调用语句的 Close 方法。
提供的上下文用于语句的准备,而不是语句的执行。
(*DB) Query
|
|
Query方法执行返回行的查询,通常是 SELECT。args 是查询中的任何占位符参数。
Query方法内部使用 context.Background。要指定上下文,请使用 QueryContext方法。
Query Example
|
|
(*DB) QueryContext <- go1.8
|
|
QueryContext方法执行返回行的查询,通常是 SELECT。args 是查询中的任何占位符参数。
QueryContext Example
|
|
(*DB) QueryRow
|
|
QueryRow方法执行一个预期返回最多一行的查询。QueryRow方法总是返回一个非空值。错误将被延迟直到调用 Row 的 Scan 方法。如果查询未选择任何行,则 *Row 的 Scan 将返回 ErrNoRows。否则,*Row 的 Scan 扫描第一行并丢弃其余行。
QueryRow方法内部使用 context.Background。要指定上下文,请使用 QueryRowContext方法。
(*DB) QueryRowContext <- go1.8
|
|
QueryRowContext方法执行一个预期返回最多一行的查询。QueryRowContext 总是返回一个非空值。错误将被延迟直到调用 Row 的 Scan 方法。如果查询未选择任何行,则 *Row 的 Scan 将返回 ErrNoRows。否则,*Row 的 Scan 扫描第一行并丢弃其余行。
QueryRowContext Example
|
|
(*DB) SetConnMaxIdleTime <- go1.15
|
|
SetConnMaxIdleTime方法设置连接的最大空闲时间。
过期的连接可能会在重新使用之前被懒惰地关闭。
如果d <= 0,则连接不会因连接的空闲时间而关闭。
(*DB) SetConnMaxLifetime <- go1.6
|
|
SetConnMaxLifetime方法设置连接可以被重用的最长时间。
到期的连接可能会在重用之前被懒惰地关闭。
如果d <= 0,则不会因连接的年龄而关闭连接。
(*DB) SetMaxIdleConns <- go1.1
|
|
SetMaxIdleConns方法设置空闲连接池中的最大连接数。
如果MaxOpenConns大于0但小于新的MaxIdleConns,则新的MaxIdleConns将被减少以匹配MaxOpenConns限制。
如果n <= 0,则不会保留空闲连接。
默认的最大空闲连接数当前为2。这可能会在将来的版本中更改。
(*DB) SetMaxOpenConns <- go1.2
|
|
SetMaxOpenConns方法设置打开到数据库的最大连接数。
如果MaxIdleConns大于0且新的MaxOpenConns小于MaxIdleConns,则MaxIdleConns将被减少以匹配新的MaxOpenConns限制。
如果n <= 0,则没有打开连接的数量限制。默认值为0(无限制)。
(*DB) Stats <- go1.5
|
|
Stats方法返回数据库统计信息。
type DBStats <- go1.5
|
|
DBStats包含数据库统计信息。
type IsolationLevel <- go1.8
|
|
IsolationLevel是在TxOptions中使用的事务隔离级别。
|
|
各种隔离级别,驱动程序可以在BeginTx中支持。如果驱动程序不支持给定的隔离级别,则可能返回错误。
参见https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels。
(IsolationLevel) String <- go1.11
|
|
String 函数返回事务隔离级别的名称。
type NamedArg <- go1.8
|
|
NamedArg 是一个命名参数。NamedArg 值可以作为参数传递给 Query 或 Exec 并绑定到 SQL 语句中相应的命名参数。
为了更简洁地创建 NamedArg 值,请参考 Named 函数。
func Named <- go1.8
|
|
Named 函数提供了一种更简洁的方式来创建 NamedArg 值。
Example usage:
使用示例:
|
|
type NullBool
|
|
NullBool结构体表示可能为空的 bool 值。NullBool 实现了 Scanner 接口,因此它可以用作扫描目标,类似于 NullString。
(*NullBool) Scan
|
|
Scan方法实现了 Scanner 接口。
(NullBool) Value
|
|
Value方法实现了 driver Valuer 接口。
type NullByte <- go1.17
|
|
NullByte结构体表示一个可能为空的 byte。NullByte 实现了 Scanner 接口,因此它可以像 NullString 一样用作扫描目标。
(*NullByte) Scan <- go1.17
|
|
Scan方法实现了 Scanner 接口。
(NullByte) Value <- go1.17
|
|
Value方法实现了 driver Valuer 接口。
type NullFloat64
|
|
NullFloat64结构体表示一个可能为空的 float64。NullFloat64 实现了 Scanner 接口,因此它可以像 NullString 一样用作扫描目标。
(*NullFloat64) Scan
|
|
Scan方法实现了 Scanner 接口。
(NullFloat64) Value
|
|
Value方法实现了 driver Valuer 接口。
type NullInt16 <- go1.17
|
|
NullInt16结构体表示可能为null的int16。NullInt16实现Scanner接口,因此它可以用作扫描目标,类似于NullString。
(*NullInt16) Scan <- go1.17
|
|
Scan方法实现Scanner接口。
(NullInt16) Value <- go1.17
|
|
Value方法实现driver Valuer接口。
type NullInt32 <- go1.13
|
|
NullInt32结构体表示可能为null的int32。NullInt32实现Scanner接口,因此它可以用作扫描目标,类似于NullString。
(*NullInt32) Scan <- go1.13
|
|
Scan方法实现Scanner接口。
(NullInt32) Value <- go1.13
|
|
Value方法实现driver Valuer接口。
type NullInt64
|
|
NullInt64结构体表示可能为null的int64。NullInt64实现Scanner接口,因此它可以用作扫描目标,类似于NullString。
(*NullInt64) Scan
|
|
Scan方法实现Scanner接口。
(NullInt64) Value
|
|
Value方法实现driver Valuer接口。
type NullString
|
|
NullString结构体表示可能为 null 的字符串。NullString 实现了 Scanner 接口,因此可以用作扫描目标:
|
|
(*NullString) Scan
|
|
Scan方法实现了 Scanner 接口。
(NullString) Value
|
|
Value方法实现了 driver Valuer 接口。
type NullTime <- go1.13
|
|
NullTime结构体表示可能为 null 的 time.Time。NullTime 实现了 Scanner 接口,因此可以用作扫描目标,类似于 NullString。
(*NullTime) Scan <- go1.13
|
|
Scan方法实现了 Scanner 接口。
(NullTime) Value <- go1.13
|
|
Value方法实现了 driver Valuer 接口。
type Out <- go1.9
|
|
Out结构体可用于从存储过程中检索 OUTPUT 值参数。
并非所有驱动程序和数据库都支持 OUTPUT 值参数。
使用示例:
|
|
type RawBytes
|
|
RawBytes 是一个字节切片,它持有数据库本身拥有的内存引用。将 RawBytes扫描后,该切片仅在下一次调用 Next方法、Scan方法或 Close方法之前有效。
type Result
|
|
Result 是对执行的 SQL 命令的摘要。
type Row
|
|
Row结构体是调用 QueryRow方法选择单行时的结果。
(*Row) Err <- go1.15
|
|
Err方法提供了一种方法,使封装的包在不调用 Scan方法的情况下检查查询错误。如果在运行查询时遇到错误,Err 返回错误(如果有)。如果此错误不是 nil,则还将从 Scan 返回此错误。
(*Row) Scan
|
|
Scan方法将匹配的行中的列复制到 dest 指向的值中。有关详细信息,请参见 Rows.Scan 的文档。如果有多行与查询匹配,则 Scan方法使用第一行并且忽略其余的行。如果没有行与查询匹配,则 Scan方法返回 ErrNoRows。
type Rows
|
|
Rowsjgt是查询的结果。它的游标在结果集的第一行之前。使用 Next方法来从一行移到另一行。
Rows Example
|
|
(*Rows) Close
|
|
Close方法方法关闭 Rows,防止进一步枚举。如果调用 Next 并且返回 false,并且没有其他结果集,则 Rows 将自动关闭,并且检查 Err 的结果就足够了。Close方法是幂等的,不会影响 Err 的结果。
(*Rows) ColumnTypes <- go1.8
|
|
ColumnTypes方法返回列信息,例如列类型、长度和可空性。某些信息可能不适用于某些驱动程序。
(*Rows) Columns
|
|
Columns方法返回列名。如果行已关闭,则 Columns方法返回错误。
(*Rows) Err
|
|
Err方法返回迭代过程中遇到的错误(如果有)。Err方法可以在显式或隐式 Close 后调用。
(*Rows) Next
|
|
Next方法准备下一个结果行以供 Scan 方法读取。它返回 true 表示成功,false 表示没有下一个结果行或准备它时发生错误。应该使用 Err 来区分这两种情况。
每次调用 Scan方法,即使是第一次调用,也必须先调用 Next方法。
(*Rows) NextResultSet <- go1.8
|
|
NextResultSet方法准备下一个结果集以供读取。它返回 true 表示还有其他结果集,或者 false 表示没有其他结果集,或者无法提前到其结果集。应该使用 Err 方法来区分这两种情况。
在调用 NextResultSet方法后,应始终在扫描之前调用 Next 方法。如果还有其他结果集,则它们可能没有结果集中的行。
(*Rows) Scan
|
|
Scan方法将当前行的列复制到 dest 指向的值中。dest 中的值数量必须与 Rows 中的列数相同。
Scan方法将从数据库中读取的列转换为 sql 包提供的以下常见 Go 类型和特殊类型:
*string
*[]byte
*int, *int8, *int16, *int32, *int64
*uint, *uint8, *uint16, *uint32, *uint64
*bool
*float32, *float64
*interface{}
*RawBytes
*Rows (cursor value)
any type implementing Scanner (see Scanner docs)
实现 Scanner 接口的任何类型(请参见 Scanner 文档) 在最简单的情况下,如果源列的值类型是整数、布尔或字符串类型 T,而 dest 的类型是 *T,则 Scan 只需通过指针分配值。
Scan 还可以在字符串和数字类型之间进行转换,只要不会丢失信息即可。虽然 Scan 将从数值数据库列中读取的所有数字字符串化为 *string,但会检查是否存在数字类型的扫描溢出。例如,值为 300 的 float64 或值为 “300” 的字符串可以扫描到 uint16,但不能扫描到 uint8,尽管 float64(255) 或 “255” 可以扫描到 uint8。有一个例外,即某些 float64 数字扫描为字符串时可能会丢失信息。通常,将浮点列扫描到 *float64 中。
如果 dest 参数的类型为 *[]byte,则 Scan 会在该参数中保存相应数据的副本。该副本由调用方拥有,可以进行修改并无限期保留。可以通过使用类型 *RawBytes 的参数来避免复制;请参阅 RawBytes 的文档以了解其使用限制。
如果一个参数的类型是 *interface{},Scan 会复制由底层驱动程序提供的值,而不进行转换。从类型 []byte 到 *interface{} 扫描时,会复制切片并且调用方拥有结果。
类型 time.Time 的源值可以扫描到类型 *time.Time、*interface{}、*string 或 *[]byte 的值中。转换为后两者时,使用 time.RFC3339Nano。
布尔类型的源值可以扫描到类型 *bool、*interface{}、string、[]byte 或 *RawBytes 中。
对于扫描到 *bool,源可以是 true、false、1、0 或可由 strconv.ParseBool 解析的字符串输入。
Scan 还可以将查询返回的游标(例如 “select cursor(select * from my_table) from dual”)转换为 *Rows 值,该值本身可以进行扫描。如果父选择查询关闭了任何游标 *Rows,则父选择查询将关闭它。
如果实现 Scanner 接口的第一个参数返回错误,则该错误将包装在返回的错误中。
type Scanner
|
|
Scanner是由Scan使用的接口。
type Stmt
|
|
Stmt结构体是一个预处理语句。Stmt对于多个goroutine并发使用是安全的。
如果在Tx或Conn上准备了Stmt,则将永远绑定到单个底层连接。 如果Tx或Conn关闭,则Stmt将变得无法使用,所有操作都将返回错误。 如果在DB上准备了Stmt,则在DB的生命周期内将保持可用。当Stmt需要在新的底层连接上执行时, 它将自动在新连接上准备自己。
Stmt Example
|
|
(*Stmt) Close
|
|
Close方法关闭该语句。
(*Stmt) Exec
|
|
Exec方法使用给定的参数执行预处理语句,并返回概括语句效果的Result。
Exec方法在内部使用context.Background。要指定上下文,请使用ExecContext方法。
(*Stmt) ExecContext <- go1.8
|
|
ExecContext方法使用给定的参数执行预处理语句,并返回概括语句效果的Result。
(*Stmt) Query
|
|
Query方法使用给定的参数执行预处理查询语句,并将查询结果作为*Rows返回。
Query方法在内部使用context.Background。要指定上下文,请使用QueryContext方法。
(*Stmt) QueryContext <- go1.8
|
|
QueryContext方法使用给定的参数执行预处理查询语句,并将查询结果作为*Rows返回。
(*Stmt) QueryRow
|
|
QueryRow方法使用给定的参数执行预处理的查询语句。如果在执行语句期间出现错误,则通过对返回的*Row调用Scan返回该错误,该*Row始终非零。如果查询未选择任何行,则*Row的Scan将返回ErrNoRows。否则,*Row的Scan将扫描第一个选定的行并丢弃其余行。
使用示例:
|
|
QueryRow方法在内部使用context.Background;要指定上下文,请使用QueryRowContext方法。
(*Stmt) QueryRowContext <- go1.8
|
|
QueryRowContext方法使用给定的参数执行预处理的查询语句。如果在执行语句期间出现错误,则通过对返回的*Row调用Scan返回该错误,该*Row始终非零。如果查询未选择任何行,则*Row的Scan将返回ErrNoRows。否则,*Row的Scan将扫描第一个选定的行并丢弃其余行。
QueryRowContext Example
|
|
type Tx
|
|
Tx结构体是数据库事务中的一个过程。
事务必须以Commit方法或Rollback方法的调用结束。
在调用Commit方法或Rollback方法之后,所有事务上的操作都会失败并返回ErrTxDone。
通过调用事务的Prepare方法或Stmt方法方法准备的语句将在调用Commit方法或Rollback方法时关闭。
(*Tx) Commit
|
|
Commit方法提交事务。
(*Tx) Exec
|
|
Exec方法执行不返回行的查询。例如:INSERT和UPDATE。
Exec方法在内部使用context.Background;要指定上下文,请使用ExecContext方法。
(*Tx) ExecContext <- go1.8
|
|
ExecContext方法执行不返回行的查询。例如:INSERT和UPDATE。
ExecContext Example
|
|
(*Tx) Prepare
|
|
Prepare方法创建一个准备好的语句以在事务中使用。
返回的语句在事务中运行,并将在事务提交或回滚时关闭。
要在此事务上使用现有的准备好的语句,请参见Tx.Stmt。
Prepare方法在内部使用context.Background; 要指定上下文,请使用PrepareContext。
Prepare Example
|
|
(*Tx) PrepareContext <- go1.8
|
|
PrepareContext方法创建一个准备好的语句以在事务中使用。
返回的语句在事务中运行,并将在事务提交或回滚时关闭。
要在此事务上使用现有的准备好的语句,请参见Tx.Stmt。
提供的上下文将用于准备上下文,而不是用于执行返回的语句。返回的语句将在事务上下文中运行。
(*Tx) Query
|
|
Query方法执行返回行的查询,通常是 SELECT。
Query方法在内部使用context.Background;要指定上下文,请使用QueryContext方法。
(*Tx) QueryContext <- go1.8
|
|
QueryContext方法执行返回行的查询,通常是 SELECT。
(*Tx) QueryRow
|
|
QueryRow方法执行预期最多返回一行的查询。QueryRow方法总是返回一个非空值。错误被延迟到调用 Row 的 Scan 方法时才会返回。如果查询未选择行,则 *Row 的 Scan 将返回 ErrNoRows。否则,*Row 的 Scan 扫描第一个选择的行并丢弃其余的行。
QueryRow方法在内部使用context.Background;要指定上下文,请使用QueryRowContext。
(*Tx) QueryRowContext <- go1.8
|
|
QueryRowContext方法执行预期最多返回一行的查询。QueryRowContext方法总是返回一个非空值。错误被延迟到调用 Row 的 Scan 方法时才会返回。如果查询未选择行,则 *Row 的 Scan 将返回 ErrNoRows。否则,*Row 的 Scan 扫描第一个选择的行并丢弃其余的行。
(*Tx) Rollback
|
|
Rollback方法中止事务。
Rollback Example
|
|
(*Tx) Stmt
|
|
Stmt方法从现有语句返回一个事务特定的准备好的语句。
示例:
|
|
返回的语句在事务中运行,并在事务提交或回滚后关闭。
Stmt在内部使用context.Background;要指定上下文,请使用StmtContext。
(*Tx) StmtContext <- go1.8
|
|
StmtContext方法从现有语句返回一个事务特定的准备语句。
Example:
|
|
提供的上下文用于准备语句,而不是执行语句。
返回的语句在事务中运行,并在事务提交或回滚后关闭。
type TxOptions <- go1.8
|
|
TxOptions保存在DB.BeginTx中使用的事务选项。
5.2 - sql/driver
driver
https://pkg.go.dev/database/sql/driver@go1.20.1
driver包定义了数据库驱动需要实现的接口,供sql包使用。
大多数代码应该使用 sql 包。
驱动程序接口随着时间的推移而发展。驱动程序应该实现 Connector 和 DriverContext 接口。Connector.Connect 和 Driver.Open 方法不应返回 ErrBadConn。如果连接已经处于无效状态(例如已关闭),则 ErrBadConn 只能从 Validator、SessionResetter 或查询方法中返回。
所有 Conn 实现都应该实现以下接口:Pinger、SessionResetter 和 Validator。
如果支持命名参数或上下文,则驱动程序的 Conn 应实现:ExecerContext、QueryerContext、ConnPrepareContext 和 ConnBeginTx。
为支持自定义数据类型,实现 NamedValueChecker。NamedValueChecker 还允许查询通过返回 ErrRemoveArgument 接受每个查询选项作为参数。
如果支持多个结果集,则 Rows 应实现 RowsNextResultSet。如果驱动程序知道返回结果中存在的类型,它应该实现以下接口:RowsColumnTypeScanType、RowsColumnTypeDatabaseTypeName、RowsColumnTypeLength、RowsColumnTypeNullable 和 RowsColumnTypePrecisionScale。给定行值也可以返回 Rows 类型,它可能表示数据库游标值。
在将连接归还给连接池之前,如果实现了 IsValid,则会调用 IsValid。在将连接用于另一个查询之前,如果实现了 ResetSession,则会调用 ResetSession。如果连接从未返回给连接池,而是立即重用,则在重用之前调用 ResetSession,但不调用 IsValid。
常量
This section is empty.
变量
|
|
Bool是ValueConverter,用于将输入值转换为布尔值。
转换规则如下:
- 布尔值不变
- 对于整数类型,1为真,0为假,其他整数为错误
- 对于字符串和[]byte,与strconv.ParseBool相同的规则
- 所有其他类型都是一个错误
|
|
DefaultParameterConverter是ValueConverter的默认实现,当Stmt未实现ColumnConverter时使用。
DefaultParameterConverter如果IsValue(arg)则直接返回其参数。否则,如果参数实现了Valuer,则使用其Value方法返回一个Value。作为后备,提供的参数的基础类型用于将其转换为Value:基础整数类型转换为int64,浮点数转换为float64,bool,string和[]byte转换为自身。如果参数是nil指针,则ConvertValue返回nil Value。如果参数是非nil指针,则对其进行取消引用,并递归调用ConvertValue。其他类型是一个错误。
|
|
如果驱动程序处于错误状态(例如服务器早期关闭连接),则驱动程序应返回ErrBadConn,以向sql包发信号。sql包应该在新连接上重试。
为了防止重复操作,如果数据库服务器可能执行操作,则不应返回ErrBadConn。即使服务器发送错误,您也不应返回ErrBadConn。
使用errors.Is检查错误。一个错误可能包装ErrBadConn或实现Is(error) bool方法。
|
|
NamedValueChecker可能会返回ErrRemoveArgument,以指示sql包不将参数传递给驱动程序查询接口。在接受特定于查询的选项或不是SQL查询参数的结构时返回。
|
|
某些可选接口的方法可能返回ErrSkip,以表示在运行时快速路径不可用,sql包应继续,就像未实现可选接口一样。仅在明确文档中记录了ErrSkip。
|
|
Int32是ValueConverter,用于将输入值转换为int64,并考虑int32值的限制。
|
|
ResultNoRows是预定义结果,驱动程序在DDL命令(如CREATE TABLE)成功时返回。它对于LastInsertId和RowsAffected都返回错误。
|
|
String是ValueConverter,用于将其输入转换为字符串。如果该值已经是字符串或[]byte,则不变。如果值是其他类型,则使用fmt.Sprintf("%v",v)进行字符串转换。
函数
func IsScanValue
|
|
IsScanValue函数等价于 IsValue。它存在是为了兼容性。
func IsValue
|
|
IsValue函数报告v是否为有效的 Value 参数类型。
类型
type Conn
|
|
Conn 是到数据库的连接。它不会被多个goroutine同时使用。
Conn 被认为是有状态的。
type ConnBeginTx <- go1.8
|
|
ConnBeginTx 使用上下文和 TxOptions 增强了 Conn 接口。
type ConnPrepareContext <- go1.8
|
|
ConnPrepareContext 通过上下文增强 Conn 接口。
type Connector <- go1.10
|
|
Connector 表示一个具有固定配置的驱动程序,并可以创建任意数量的等效 Conns 供多个 goroutine 使用。
可以将 Connector 传递给 sql.OpenDB,以允许驱动程序实现其自己的 sql.DB 构造函数,或者由 DriverContext 的 OpenConnector 方法返回,以允许驱动程序访问上下文并避免重复解析驱动程序配置。
如果 Connector 实现了 io.Closer,则 sql 包的 DB.Close 方法将调用 Close 并返回错误(如果有)。
type Driver
|
|
Driver 是必须由数据库驱动程序实现的接口。
数据库驱动程序可以实现 DriverContext,以便访问上下文并仅解析一次名称以获得连接池,而不是每个连接都解析一次。
type DriverContext <- go1.10
|
|
如果 Driver 实现了 DriverContext 接口,那么 sql.DB 将调用 OpenConnector 来获取 Connector,并调用该 Connector 的 Connect 方法来获取每个所需的连接,而不是为每个连接调用 Driver 的 Open 方法。这个两步的过程允许驱动程序只解析一次名称,并且提供对每个 Conn 的上下文访问。
type ExecerContext <- go1.8
|
|
ExecerContext 是一个可选接口,可以由 Conn 实现。
如果 Conn 没有实现 ExecerContext,则 sql 包的 DB.Exec 将退回到 Execer;如果 Conn 也没有实现 Execer,则 DB.Exec 将首先准备查询,执行语句,然后关闭语句。
ExecContext 可能返回 ErrSkip。
ExecContext 必须遵守上下文超时,并在上下文取消时返回。
type IsolationLevel <- go1.8
|
|
IsolationLevel 是存储在 TxOptions 中的事务隔离级别。
这个类型应该被认为与 sql.IsolationLevel 相同,以及其上定义的任何值。
type NamedValue <- go1.8
|
|
NamedValue 持有值的名称和值。
type NamedValueChecker <- go1.9
|
|
NamedValueChecker 可以由 Conn 或 Stmt 可选实现。它为驱动程序提供了更多的控制权,以处理超出默认的 Value 类型允许的 Go 和数据库类型。
sql包会按照以下顺序检查值检查器,并在找到第一个匹配项时停止:Stmt.NamedValueChecker、Conn.NamedValueChecker、Stmt.ColumnConverter和DefaultParameterConverter。
如果CheckNamedValue返回ErrRemoveArgument,则NamedValue不会包含在最终查询参数中。这可用于向查询本身传递特殊选项。
如果返回ErrSkip,则对于该参数将使用列转换器错误检查路径。驱动程序可能会在耗尽其自己的特殊情况后返回ErrSkip。
type NotNull
|
|
NotNull结构体是一种类型,通过禁止nil值但否则委托给另一个ValueConverter来实现ValueConverter。
(NotNull) ConvertValue
|
|
type Null
|
|
Null结构体是一种类型,通过允许nil值但否则委托给另一个ValueConverter来实现ValueConverter。
(Null) ConvertValue
|
|
type Pinger <- go1.8
|
|
Pinger是Conn可能实现的一个可选接口。
如果Conn未实现Pinger,则sql包的DB.Ping和DB.PingContext将检查是否至少有一个Conn可用。
如果Conn.Ping返回ErrBadConn,则DB.Ping和DB.PingContext将从池中删除Conn。
type QueryerContext <- go1.8
|
|
QueryerContext是Conn可能实现的一个可选接口。
如果Conn未实现QueryerContext,则sql包的DB.Query将回退到Queryer;如果Conn也未实现Queryer,则DB.Query将首先准备查询,执行语句,然后关闭语句。
QueryContext可能会返回ErrSkip。
QueryContext必须遵守上下文超时并在取消上下文时返回。
type Result
|
|
Result接口表示一个查询操作的结果。
type Rows
|
|
Rows接口是一个已执行查询的结果集迭代器。
type RowsAffected
|
|
RowsAffected 表示执行 INSERT 或 UPDATE 操作所影响的行数,实现了 Result 接口。
(RowsAffected) LastInsertId
|
|
(RowsAffected) RowsAffected
|
|
type RowsColumnTypeDatabaseTypeName <- go1.8
|
|
RowsColumnTypeDatabaseTypeName接口可以被 Rows 实现。它应该返回数据库系统类型名称,但不包括长度信息。类型名称应大写。以下是各种类型的返回示例:“VARCHAR”、“NVARCHAR”、“VARCHAR2”、“CHAR”、“TEXT”、“DECIMAL”、“SMALLINT”、“INT”、“BIGINT”、“BOOL”、"[]BIGINT"、“JSONB”、“XML”、“TIMESTAMP”。
type RowsColumnTypeLength <- go1.8
|
|
RowsColumnTypeLength接口可以被 Rows 实现。如果列是变长类型,则它应返回列类型的长度。如果列不是变长类型,则应该返回 false。如果长度除系统限制外不受限制,则应返回 math.MaxInt64。以下是各种类型的返回示例:
TEXT (math.MaxInt64, true)
varchar(10) (10, true)
nvarchar(10) (10, true)
decimal (0, false)
int (0, false)
bytea(30) (30, true)
type RowsColumnTypeNullable <- go1.8
|
|
RowsColumnTypeNullable接口是由Rows实现的可选接口。如果已知该列可以为null,则可为空值应为true;如果已知该列不可为空,则为空值为false。如果列的可空性未知,则ok应为false。
type RowsColumnTypePrecisionScale <- go1.8
|
|
RowsColumnTypePrecisionScale接口是由Rows实现的可选接口。它应返回十进制类型的精度和刻度。如果不适用,则应将ok设置为false。以下是各种类型的返回值示例:
decimal(38, 4) (38, 4, true)
int (0, 0, false)
decimal (math.MaxInt64, math.MaxInt64, true)
type RowsColumnTypeScanType <- go1.8
|
|
RowsColumnTypeScanType接口是由Rows实现的可选接口。它应返回可以用于扫描类型的值类型。例如,对于数据库列类型"bigint",这应返回"reflect.TypeOf(int64(0))"。
type RowsNextResultSet <- go1.8
|
|
RowsNextResultSet接口通过提供一种信号方式来扩展Rows接口,以使驱动程序前进到下一个结果集。
type SessionResetter <- go1.10
|
|
SessionResetter接口可以由Conn实现,以允许驱动程序重置与连接相关的会话状态并发出坏连接信号。
type Stmt
|
|
Stmt接口是预处理语句。它绑定到Conn,不能被多个goroutine同时使用。
type StmtExecContext <- go1.8
|
|
StmtExecContext接口通过提供带有上下文的Exec来增强Stmt接口。
type StmtQueryContext <- go1.8
|
|
StmtQueryContext接口通过提供带有上下文的Query来增强Stmt接口。
type Tx
|
|
Tx 是事务。
type TxOptions <- go1.8
|
|
TxOptions结构体存储事务的选项。
此类型应被认为与 sql.TxOptions 相同。
type Validator <- go1.15
|
|
Validator接口可以被 Conn 实现,以允许驱动程序表明连接是否有效或是否应丢弃。
如果实现了 Validator,则驱动程序可能会从查询中返回基础错误,即使连接应该由连接池丢弃。
type Value
|
|
Value类型是驱动程序必须能够处理的值。它可以是 nil、由数据库驱动程序的 NamedValueChecker 接口处理的类型,或是以下类型的实例
int64
float64
bool
[]byte
string
time.Time
如果驱动程序支持游标,则返回的 Value 还可以在此包中实现 Rows 接口。例如,当用户选择类似于"select cursor(select * from my_table) from dual"这样的光标时。如果从选择中的 Rows 被关闭,则光标 Rows 也将被关闭。
type ValueConverter
|
|
ValueConverter接口是提供 ConvertValue 方法的接口。
驱动程序包提供了 ValueConverter 的各种实现,以提供驱动程序之间的一致的转换实现。ValueConverter 有以下几个用途:
- 将 sql 包提供的 Value 类型转换为数据库表的特定列类型,并确保其适合,例如确保特定 int64 适合于表的 uint16 列。
- 将从数据库中给出的值转换为驱动程序 Value 类型之一。
- 由 sql 包,在扫描中将驱动程序的 Value 类型转换为用户的类型。
type Valuer
|
|
Valuer接口是提供 Value 方法的接口。
实现 Valuer 接口的类型能够将自身转换为驱动程序 Value。
6 - debug
6.1 - buildinfo
buildinfo
https://pkg.go.dev/debug/buildinfo@go1.20.1
Package buildinfo provides access to information embedded in a Go binary about how it was built. This includes the Go toolchain version, and the set of modules used (for binaries built in module mode).
包buildinfo提供了对嵌入Go二进制文件中的信息的访问,了解它是如何构建的。这包括Go工具链的版本,以及所使用的模块集(对于以模块模式构建的二进制文件)。
Build information is available for the currently running binary in runtime/debug.ReadBuildInfo.
在runtime/debug.ReadBuildInfo中,当前运行的二进制文件可以获得构建信息。
常量
This section is empty.
变量
This section is empty.
函数
This section is empty.
类型
type BuildInfo
|
|
Type alias for build info. We cannot move the types here, since runtime/debug would need to import this package, which would make it a much larger dependency.
构建信息的类型别名。我们不能把类型移到这里,因为 runtime/debug 需要导入这个包,这将使它成为一个更大的依赖关系。
func Read
|
|
Read returns build information embedded in a Go binary file accessed through the given ReaderAt. Most information is only available for binaries built with module support.
Read 返回嵌入在通过给定的ReaderAt访问的Go二进制文件中的构建信息。大多数信息只适用于有模块支持的二进制文件。
func ReadFile
|
|
ReadFile returns build information embedded in a Go binary file at the given path. Most information is only available for binaries built with module support.
ReadFile返回嵌入在给定路径的Go二进制文件中的构建信息。大多数信息只适用于有模块支持的二进制文件。
6.2 - dwarf
dwarf
https://pkg.go.dev/debug/dwarf@go1.20.1
Package dwarf provides access to DWARF debugging information loaded from executable files, as defined in the DWARF 2.0 Standard at http://dwarfstd.org/doc/dwarf-2.0.0.pdf.
Security
This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.
常量
This section is empty.
变量
|
|
ErrUnknownPC is the error returned by LineReader.ScanPC when the seek PC is not covered by any entry in the line table.
函数
This section is empty.
类型
type AddrType
|
|
An AddrType represents a machine address type.
type ArrayType
|
|
An ArrayType represents a fixed size array type.
(*ArrayType) Size
|
|
(*ArrayType) String
|
|
type Attr
|
|
An Attr identifies the attribute type in a DWARF Entry’s Field.
|
|
(Attr) GoString
|
|
(Attr) String
|
|
type BasicType
|
|
A BasicType holds fields common to all basic types.
See the documentation for StructField for more info on the interpretation of the BitSize/BitOffset/DataBitOffset fields.
(*BasicType) Basic
|
|
(*BasicType) String
|
|
type BoolType
|
|
A BoolType represents a boolean type.
type CharType
|
|
A CharType represents a signed character type.
type Class <- go1.5
|
|
A Class is the DWARF 4 class of an attribute value.
In general, a given attribute’s value may take on one of several possible classes defined by DWARF, each of which leads to a slightly different interpretation of the attribute.
DWARF version 4 distinguishes attribute value classes more finely than previous versions of DWARF. The reader will disambiguate coarser classes from earlier versions of DWARF into the appropriate DWARF 4 class. For example, DWARF 2 uses “constant” for constants as well as all types of section offsets, but the reader will canonicalize attributes in DWARF 2 files that refer to section offsets to one of the Class*Ptr classes, even though these classes were only defined in DWARF 3.
|
|
(Class) GoString <- go1.5
|
|
(Class) String <- go1.5
|
|
type CommonType
|
|
A CommonType holds fields common to multiple types. If a field is not known or not applicable for a given type, the zero value is used.
(*CommonType) Common
|
|
(*CommonType) Size
|
|
type ComplexType
|
|
A ComplexType represents a complex floating point type.
type Data
|
|
Data represents the DWARF debugging information loaded from an executable file (for example, an ELF or Mach-O executable).
func New
|
|
New returns a new Data object initialized from the given parameters. Rather than calling this function directly, clients should typically use the DWARF method of the File type of the appropriate package debug/elf, debug/macho, or debug/pe.
The []byte arguments are the data from the corresponding debug section in the object file; for example, for an ELF object, abbrev is the contents of the “.debug_abbrev” section.
(*Data) AddSection <- go1.14
|
|
AddSection adds another DWARF section by name. The name should be a DWARF section name such as “.debug_addr”, “.debug_str_offsets”, and so forth. This approach is used for new DWARF sections added in DWARF 5 and later.
(*Data) AddTypes <- go1.3
|
|
AddTypes will add one .debug_types section to the DWARF data. A typical object with DWARF version 4 debug info will have multiple .debug_types sections. The name is used for error reporting only, and serves to distinguish one .debug_types section from another.
(*Data) LineReader <- go1.5
|
|
LineReader returns a new reader for the line table of compilation unit cu, which must be an Entry with tag TagCompileUnit.
If this compilation unit has no line table, it returns nil, nil.
(*Data) Ranges <- go1.7
|
|
Ranges returns the PC ranges covered by e, a slice of [low,high) pairs. Only some entry types, such as TagCompileUnit or TagSubprogram, have PC ranges; for others, this will return nil with no error.
(*Data) Reader
|
|
Reader returns a new Reader for Data. The reader is positioned at byte offset 0 in the DWARF “info” section.
(*Data) Type
|
|
Type reads the type at off in the DWARF “info” section.
type DecodeError
|
|
(DecodeError) Error
|
|
type DotDotDotType
|
|
A DotDotDotType represents the variadic … function parameter.
(*DotDotDotType) String
|
|
type Entry
|
|
An entry is a sequence of attribute/value pairs.
(*Entry) AttrField <- go1.5
|
|
AttrField returns the Field associated with attribute Attr in Entry, or nil if there is no such attribute.
(*Entry) Val
|
|
Val returns the value associated with attribute Attr in Entry, or nil if there is no such attribute.
A common idiom is to merge the check for nil return with the check that the value has the expected dynamic type, as in:
v, ok := e.Val(AttrSibling).(int64)
type EnumType
|
|
An EnumType represents an enumerated type. The only indication of its native integer type is its ByteSize (inside CommonType).
(*EnumType) String
|
|
type EnumValue
|
|
An EnumValue represents a single enumeration value.
type Field
|
|
A Field is a single attribute/value pair in an Entry.
A value can be one of several “attribute classes” defined by DWARF. The Go types corresponding to each class are:
DWARF class Go type Class
----------- ------- -----
address uint64 ClassAddress
block []byte ClassBlock
constant int64 ClassConstant
flag bool ClassFlag
reference
to info dwarf.Offset ClassReference
to type unit uint64 ClassReferenceSig
string string ClassString
exprloc []byte ClassExprLoc
lineptr int64 ClassLinePtr
loclistptr int64 ClassLocListPtr
macptr int64 ClassMacPtr
rangelistptr int64 ClassRangeListPtr
For unrecognized or vendor-defined attributes, Class may be ClassUnknown.
type FloatType
|
|
A FloatType represents a floating point type.
type FuncType
|
|
A FuncType represents a function type.
(*FuncType) String
|
|
type IntType
|
|
An IntType represents a signed integer type.
type LineEntry <- go1.5
|
|
A LineEntry is a row in a DWARF line table.
type LineFile <- go1.5
|
|
A LineFile is a source file referenced by a DWARF line table entry.
type LineReader <- go1.5
|
|
A LineReader reads a sequence of LineEntry structures from a DWARF “line” section for a single compilation unit. LineEntries occur in order of increasing PC and each LineEntry gives metadata for the instructions from that LineEntry’s PC to just before the next LineEntry’s PC. The last entry will have its EndSequence field set.
(*LineReader) Files <- go1.14
|
|
Files returns the file name table of this compilation unit as of the current position in the line table. The file name table may be referenced from attributes in this compilation unit such as AttrDeclFile.
Entry 0 is always nil, since file index 0 represents “no file”.
The file name table of a compilation unit is not fixed. Files returns the file table as of the current position in the line table. This may contain more entries than the file table at an earlier position in the line table, though existing entries never change.
(*LineReader) Next <- go1.5
|
|
Next sets *entry to the next row in this line table and moves to the next row. If there are no more entries and the line table is properly terminated, it returns io.EOF.
Rows are always in order of increasing entry.Address, but entry.Line may go forward or backward.
(*LineReader) Reset <- go1.5
|
|
Reset repositions the line table reader at the beginning of the line table.
(*LineReader) Seek <- go1.5
|
|
Seek restores the line table reader to a position returned by Tell.
The argument pos must have been returned by a call to Tell on this line table.
(*LineReader) SeekPC <- go1.5
|
|
SeekPC sets *entry to the LineEntry that includes pc and positions the reader on the next entry in the line table. If necessary, this will seek backwards to find pc.
If pc is not covered by any entry in this line table, SeekPC returns ErrUnknownPC. In this case, *entry and the final seek position are unspecified.
Note that DWARF line tables only permit sequential, forward scans. Hence, in the worst case, this takes time linear in the size of the line table. If the caller wishes to do repeated fast PC lookups, it should build an appropriate index of the line table.
(*LineReader) Tell <- go1.5
|
|
Tell returns the current position in the line table.
type LineReaderPos <- go1.5
|
|
A LineReaderPos represents a position in a line table.
type Offset
|
|
An Offset represents the location of an Entry within the DWARF info. (See Reader.Seek.)
type PtrType
|
|
A PtrType represents a pointer type.
(*PtrType) String
|
|
type QualType
|
|
A QualType represents a type that has the C/C++ “const”, “restrict”, or “volatile” qualifier.
(*QualType) Size
|
|
(*QualType) String
|
|
type Reader
|
|
A Reader allows reading Entry structures from a DWARF “info” section. The Entry structures are arranged in a tree. The Reader’s Next function return successive entries from a pre-order traversal of the tree. If an entry has children, its Children field will be true, and the children follow, terminated by an Entry with Tag 0.
(*Reader) AddressSize <- go1.5
|
|
AddressSize returns the size in bytes of addresses in the current compilation unit.
(*Reader) ByteOrder <- go1.14
|
|
ByteOrder returns the byte order in the current compilation unit.
(*Reader) Next
|
|
Next reads the next entry from the encoded entry stream. It returns nil, nil when it reaches the end of the section. It returns an error if the current offset is invalid or the data at the offset cannot be decoded as a valid Entry.
(*Reader) Seek
|
|
Seek positions the Reader at offset off in the encoded entry stream. Offset 0 can be used to denote the first entry.
(*Reader) SeekPC <- go1.7
|
|
SeekPC returns the Entry for the compilation unit that includes pc, and positions the reader to read the children of that unit. If pc is not covered by any unit, SeekPC returns ErrUnknownPC and the position of the reader is undefined.
Because compilation units can describe multiple regions of the executable, in the worst case SeekPC must search through all the ranges in all the compilation units. Each call to SeekPC starts the search at the compilation unit of the last call, so in general looking up a series of PCs will be faster if they are sorted. If the caller wishes to do repeated fast PC lookups, it should build an appropriate index using the Ranges method.
(*Reader) SkipChildren
|
|
SkipChildren skips over the child entries associated with the last Entry returned by Next. If that Entry did not have children or Next has not been called, SkipChildren is a no-op.
type StructField
|
|
A StructField represents a field in a struct, union, or C++ class type.
Bit Fields
The BitSize, BitOffset, and DataBitOffset fields describe the bit size and offset of data members declared as bit fields in C/C++ struct/union/class types.
BitSize is the number of bits in the bit field.
DataBitOffset, if non-zero, is the number of bits from the start of the enclosing entity (e.g. containing struct/class/union) to the start of the bit field. This corresponds to the DW_AT_data_bit_offset DWARF attribute that was introduced in DWARF 4.
BitOffset, if non-zero, is the number of bits between the most significant bit of the storage unit holding the bit field to the most significant bit of the bit field. Here “storage unit” is the type name before the bit field (for a field “unsigned x:17”, the storage unit is “unsigned”). BitOffset values can vary depending on the endianness of the system. BitOffset corresponds to the DW_AT_bit_offset DWARF attribute that was deprecated in DWARF 4 and removed in DWARF 5.
At most one of DataBitOffset and BitOffset will be non-zero; DataBitOffset/BitOffset will only be non-zero if BitSize is non-zero. Whether a C compiler uses one or the other will depend on compiler vintage and command line options.
Here is an example of C/C++ bit field use, along with what to expect in terms of DWARF bit offset info. Consider this code:
struct S {
int q;
int j:5;
int k:6;
int m:5;
int n:8;
} s;
For the code above, one would expect to see the following for DW_AT_bit_offset values (using GCC 8):
Little | Big
Endian | Endian
|
"j": 27 | 0
"k": 21 | 5
"m": 16 | 11
"n": 8 | 16
Note that in the above the offsets are purely with respect to the containing storage unit for j/k/m/n – these values won’t vary based on the size of prior data members in the containing struct.
If the compiler emits DW_AT_data_bit_offset, the expected values would be:
"j": 32
"k": 37
"m": 43
"n": 48
Here the value 32 for “j” reflects the fact that the bit field is preceded by other data members (recall that DW_AT_data_bit_offset values are relative to the start of the containing struct). Hence DW_AT_data_bit_offset values can be quite large for structs with many fields.
DWARF also allow for the possibility of base types that have non-zero bit size and bit offset, so this information is also captured for base types, but it is worth noting that it is not possible to trigger this behavior using mainstream languages.
type StructType
|
|
A StructType represents a struct, union, or C++ class type.
(*StructType) Defn
|
|
(*StructType) String
|
|
type Tag
|
|
A Tag is the classification (the type) of an Entry.
|
|
(Tag) GoString
|
|
(Tag) String
|
|
type Type
|
|
A Type conventionally represents a pointer to any of the specific Type structures (CharType, StructType, etc.).
type TypedefType
|
|
A TypedefType represents a named type.
(*TypedefType) Size
|
|
(*TypedefType) String
|
|
type UcharType
|
|
A UcharType represents an unsigned character type.
type UintType
|
|
A UintType represents an unsigned integer type.
type UnspecifiedType <- go1.4
|
|
An UnspecifiedType represents an implicit, unknown, ambiguous or nonexistent type.
type UnsupportedType <- go1.13
|
|
An UnsupportedType is a placeholder returned in situations where we encounter a type that isn’t supported.
(*UnsupportedType) String <- go1.13
|
|
type VoidType
|
|
A VoidType represents the C void type.
(*VoidType) String
|
|
6.3 - elf
elf
https://pkg.go.dev/debug/elf@go1.20.1
Package elf implements access to ELF object files.
Security
This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.
常量
|
|
Indexes into the Header.Ident array.
|
|
Magic number for the elf trampoline, chosen wisely to be an immediate value.
|
|
Initial magic number for ELF files.
|
|
|
|
变量
|
|
ErrNoSymbols is returned by File.Symbols and File.DynamicSymbols if there is no such section in the File.
函数
func R_INFO
|
|
func R_INFO32
|
|
func R_SYM32
|
|
func R_SYM64
|
|
func R_TYPE32
|
|
func R_TYPE64
|
|
func ST_INFO
|
|
类型
type Chdr32 <- go1.6
|
|
ELF32 Compression header.
type Chdr64 <- go1.6
|
|
ELF64 Compression header.
type Class
|
|
Class is found in Header.Ident[EI_CLASS] and Header.Class.
|
|
(Class) GoString
|
|
(Class) String
|
|
type CompressionType <- go1.6
|
|
Section compression type.
|
|
(CompressionType) GoString <- go1.6
|
|
(CompressionType) String <- go1.6
|
|
type Data
|
|
Data is found in Header.Ident[EI_DATA] and Header.Data.
|
|
(Data) GoString
|
|
(Data) String
|
|
type Dyn32
|
|
ELF32 Dynamic structure. The “.dynamic” section contains an array of them.
type Dyn64
|
|
ELF64 Dynamic structure. The “.dynamic” section contains an array of them.
type DynFlag
|
|
DT_FLAGS values.
|
|
(DynFlag) GoString
|
|
(DynFlag) String
|
|
type DynTag
|
|
Dyn.Tag
|
|
(DynTag) GoString
|
|
(DynTag) String
|
|
type File
|
|
A File represents an open ELF file.
func NewFile
|
|
NewFile creates a new File for accessing an ELF binary in an underlying reader. The ELF binary is expected to start at position 0 in the ReaderAt.
func Open
|
|
Open opens the named file using os.Open and prepares it for use as an ELF binary.
(*File) Close
|
|
Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.
(*File) DWARF
|
|
(*File) DynString <- go1.1
|
|
DynString returns the strings listed for the given tag in the file’s dynamic section.
The tag must be one that takes string values: DT_NEEDED, DT_SONAME, DT_RPATH, or DT_RUNPATH.
(*File) DynamicSymbols <- go1.4
|
|
DynamicSymbols returns the dynamic symbol table for f. The symbols will be listed in the order they appear in f.
If f has a symbol version table, the returned Symbols will have initialized Version and Library fields.
For compatibility with Symbols, DynamicSymbols omits the null symbol at index 0. After retrieving the symbols as symtab, an externally supplied index x corresponds to symtab[x-1], not symtab[x].
(*File) ImportedLibraries
|
|
ImportedLibraries returns the names of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.
(*File) ImportedSymbols
|
|
ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time. It does not return weak symbols.
(*File) Section
|
|
Section returns a section with the given name, or nil if no such section exists.
(*File) SectionByType
|
|
SectionByType returns the first section in f with the given type, or nil if there is no such section.
(*File) Symbols
|
|
Symbols returns the symbol table for f. The symbols will be listed in the order they appear in f.
For compatibility with Go 1.0, Symbols omits the null symbol at index 0. After retrieving the symbols as symtab, an externally supplied index x corresponds to symtab[x-1], not symtab[x].
type FileHeader
|
|
A FileHeader represents an ELF file header.
type FormatError
|
|
(*FormatError) Error
|
|
type Header32
|
|
ELF32 File header.
type Header64
|
|
ELF64 file header.
type ImportedSymbol
|
|
type Machine
|
|
Machine is found in Header.Machine.
|
|
(Machine) GoString
|
|
(Machine) String
|
|
type NType
|
|
NType values; used in core files.
|
|
(NType) GoString
|
|
(NType) String
|
|
type OSABI
|
|
OSABI is found in Header.Ident[EI_OSABI] and Header.OSABI.
|
|
(OSABI) GoString
|
|
(OSABI) String
|
|
type Prog
|
|
A Prog represents a single ELF program header in an ELF binary.
(*Prog) Open
|
|
Open returns a new ReadSeeker reading the ELF program body.
type Prog32
|
|
ELF32 Program header.
type Prog64
|
|
ELF64 Program header.
type ProgFlag
|
|
Prog.Flag
|
|
(ProgFlag) GoString
|
|
(ProgFlag) String
|
|
type ProgHeader
|
|
A ProgHeader represents a single ELF program header.
type ProgType
|
|
Prog.Type
|
|
(ProgType) GoString
|
|
(ProgType) String
|
|
type R_386
|
|
Relocation types for 386.
|
|
(R_386) GoString
|
|
(R_386) String
|
|
type R_390 <- go1.7
|
|
Relocation types for s390x processors.
|
|
(R_390) GoString <- go1.7
|
|
(R_390) String <- go1.7
|
|
type R_AARCH64 <- go1.4
|
|
Relocation types for AArch64 (aka arm64)
|
|
(R_AARCH64) GoString <- go1.4
|
|
(R_AARCH64) String <- go1.4
|
|
type R_ALPHA
|
|
Relocation types for Alpha.
|
|
(R_ALPHA) GoString
|
|
(R_ALPHA) String
|
|
type R_ARM
|
|
Relocation types for ARM.
|
|
(R_ARM) GoString
|
|
(R_ARM) String
|
|
type R_LARCH <- go1.19
|
|
Relocation types for LoongArch.
|
|
(R_LARCH) GoString <- go1.19
|
|
(R_LARCH) String <- go1.19
|
|
type R_MIPS <- go1.6
|
|
Relocation types for MIPS.
|
|
(R_MIPS) GoString <- go1.6
|
|
(R_MIPS) String <- go1.6
|
|
type R_PPC
|
|
Relocation types for PowerPC.
Values that are shared by both R_PPC and R_PPC64 are prefixed with R_POWERPC_ in the ELF standard. For the R_PPC type, the relevant shared relocations have been renamed with the prefix R_PPC_. The original name follows the value in a comment.
|
|
(R_PPC) GoString
|
|
(R_PPC) String
|
|
type R_PPC64 <- go1.5
|
|
Relocation types for 64-bit PowerPC or Power Architecture processors.
Values that are shared by both R_PPC and R_PPC64 are prefixed with R_POWERPC_ in the ELF standard. For the R_PPC64 type, the relevant shared relocations have been renamed with the prefix R_PPC64_. The original name follows the value in a comment.
|
|
(R_PPC64) GoString <- go1.5
|
|
(R_PPC64) String <- go1.5
|
|
type R_RISCV <- go1.11
|
|
Relocation types for RISC-V processors.
|
|
(R_RISCV) GoString <- go1.11
|
|
(R_RISCV) String <- go1.11
|
|
type R_SPARC
|
|
Relocation types for SPARC.
|
|
(R_SPARC) GoString
|
|
(R_SPARC) String
|
|
type R_X86_64
|
|
Relocation types for x86-64.
|
|
(R_X86_64) GoString
|
|
(R_X86_64) String
|
|
type Rel32
|
|
ELF32 Relocations that don’t need an addend field.
type Rel64
|
|
ELF64 relocations that don’t need an addend field.
type Rela32
|
|
ELF32 Relocations that need an addend field.
type Rela64
|
|
ELF64 relocations that need an addend field.
type Section
|
|
A Section represents a single section in an ELF file.
(*Section) Data
|
|
Data reads and returns the contents of the ELF section. Even if the section is stored compressed in the ELF file, Data returns uncompressed data.
For an SHT_NOBITS section, Data always returns a non-nil error.
(*Section) Open
|
|
Open returns a new ReadSeeker reading the ELF section. Even if the section is stored compressed in the ELF file, the ReadSeeker reads uncompressed data.
For an SHT_NOBITS section, all calls to the opened reader will return a non-nil error.
type Section32
|
|
ELF32 Section header.
type Section64
|
|
ELF64 Section header.
type SectionFlag
|
|
Section flags.
|
|
(SectionFlag) GoString
|
|
(SectionFlag) String
|
|
type SectionHeader
|
|
A SectionHeader represents a single ELF section header.
type SectionIndex
|
|
Special section indices.
|
|
(SectionIndex) GoString
|
|
(SectionIndex) String
|
|
type SectionType
|
|
Section type.
|
|
(SectionType) GoString
|
|
(SectionType) String
|
|
type Sym32
|
|
ELF32 Symbol.
type Sym64
|
|
ELF64 symbol table entries.
type SymBind
|
|
Symbol Binding - ELFNN_ST_BIND - st_info
|
|
func ST_BIND
|
|
(SymBind) GoString
|
|
(SymBind) String
|
|
type SymType
|
|
Symbol type - ELFNN_ST_TYPE - st_info
|
|
func ST_TYPE
|
|
(SymType) GoString
|
|
(SymType) String
|
|
type SymVis
|
|
Symbol visibility - ELFNN_ST_VISIBILITY - st_other
|
|
func ST_VISIBILITY
|
|
(SymVis) GoString
|
|
(SymVis) String
|
|
type Symbol
|
|
A Symbol represents an entry in an ELF symbol table section.
type Type
|
|
Type is found in Header.Type.
|
|
(Type) GoString
|
|
(Type) String
|
|
type Version
|
|
Version is found in Header.Ident[EI_VERSION] and Header.Version.
|
|
(Version) GoString
|
|
(Version) String
|
|
6.4 - gosym
gosym
https://pkg.go.dev/debug/gosym@go1.20.1
Package gosym implements access to the Go symbol and line number tables embedded in Go binaries generated by the gc compilers.
常量
This section is empty.
变量
This section is empty.
函数
This section is empty.
类型
type DecodingError
|
|
DecodingError represents an error during the decoding of the symbol table.
(*DecodingError) Error
|
|
type Func
|
|
A Func collects information about a single function.
type LineTable
|
|
A LineTable is a data structure mapping program counters to line numbers.
In Go 1.1 and earlier, each function (represented by a Func) had its own LineTable, and the line number corresponded to a numbering of all source lines in the program, across all files. That absolute line number would then have to be converted separately to a file name and line number within the file.
In Go 1.2, the format of the data changed so that there is a single LineTable for the entire program, shared by all Funcs, and there are no absolute line numbers, just line numbers within specific files.
For the most part, LineTable’s methods should be treated as an internal detail of the package; callers should use the methods on Table instead.
func NewLineTable
|
|
NewLineTable returns a new PC/line table corresponding to the encoded data. Text must be the start address of the corresponding text segment.
Example
|
|
Example
|
|
type Obj
|
|
An Obj represents a collection of functions in a symbol table.
The exact method of division of a binary into separate Objs is an internal detail of the symbol table format.
In early versions of Go each source file became a different Obj.
In Go 1 and Go 1.1, each package produced one Obj for all Go sources and one Obj per C source file.
In Go 1.2, there is a single Obj for the entire program.
type Sym
|
|
A Sym represents a single symbol table entry.
(*Sym) BaseName
|
|
BaseName returns the symbol name without the package or receiver name.
(*Sym) PackageName
|
|
PackageName returns the package part of the symbol name, or the empty string if there is none.
(*Sym) ReceiverName
|
|
ReceiverName returns the receiver type name of this symbol, or the empty string if there is none. A receiver name is only detected in the case that s.Name is fully-specified with a package name.
(*Sym) Static
|
|
Static reports whether this symbol is static (not visible outside its file).
type Table
|
|
Table represents a Go symbol table. It stores all of the symbols decoded from the program and provides methods to translate between symbols, names, and addresses.
func NewTable
|
|
NewTable decodes the Go symbol table (the “.gosymtab” section in ELF), returning an in-memory representation. Starting with Go 1.3, the Go symbol table no longer includes symbol data.
(*Table) LineToPC
|
|
LineToPC looks up the first program counter on the given line in the named file. It returns UnknownPathError or UnknownLineError if there is an error looking up this line.
(*Table) LookupFunc
|
|
LookupFunc returns the text, data, or bss symbol with the given name, or nil if no such symbol is found.
(*Table) LookupSym
|
|
LookupSym returns the text, data, or bss symbol with the given name, or nil if no such symbol is found.
(*Table) PCToFunc
|
|
PCToFunc returns the function containing the program counter pc, or nil if there is no such function.
(*Table) PCToLine
|
|
PCToLine looks up line number information for a program counter. If there is no information, it returns fn == nil.
(*Table) SymByAddr
|
|
SymByAddr returns the text, data, or bss symbol starting at the given address.
type UnknownFileError
|
|
UnknownFileError represents a failure to find the specific file in the symbol table.
(UnknownFileError) Error
|
|
type UnknownLineError
|
|
UnknownLineError represents a failure to map a line to a program counter, either because the line is beyond the bounds of the file or because there is no code on the given line.
(*UnknownLineError) Error
|
|
6.5 - macho
macho
https://pkg.go.dev/debug/macho@go1.20.1
Package macho implements access to Mach-O object files.
Security
This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.
常量
|
|
|
|
变量
|
|
ErrNotFat is returned from NewFatFile or OpenFat when the file is not a universal binary but may be a thin binary, based on its magic number.
函数
This section is empty.
类型
type Cpu
|
|
A Cpu is a Mach-O cpu type.
|
|
(Cpu) GoString
|
|
(Cpu) String
|
|
type Dylib
|
|
A Dylib represents a Mach-O load dynamic library command.
type DylibCmd
|
|
A DylibCmd is a Mach-O load dynamic library command.
type Dysymtab
|
|
A Dysymtab represents a Mach-O dynamic symbol table command.
type DysymtabCmd
|
|
A DysymtabCmd is a Mach-O dynamic symbol table command.
type FatArch <- go1.3
|
|
A FatArch is a Mach-O File inside a FatFile.
type FatArchHeader <- go1.3
|
|
A FatArchHeader represents a fat header for a specific image architecture.
type FatFile <- go1.3
|
|
A FatFile is a Mach-O universal binary that contains at least one architecture.
func NewFatFile <- go1.3
|
|
NewFatFile creates a new FatFile for accessing all the Mach-O images in a universal binary. The Mach-O binary is expected to start at position 0 in the ReaderAt.
func OpenFat <- go1.3
|
|
OpenFat opens the named file using os.Open and prepares it for use as a Mach-O universal binary.
(*FatFile) Close <- go1.3
|
|
type File
|
|
A File represents an open Mach-O file.
func NewFile
|
|
NewFile creates a new File for accessing a Mach-O binary in an underlying reader. The Mach-O binary is expected to start at position 0 in the ReaderAt.
func Open
|
|
Open opens the named file using os.Open and prepares it for use as a Mach-O binary.
(*File) Close
|
|
Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.
(*File) DWARF
|
|
DWARF returns the DWARF debug information for the Mach-O file.
(*File) ImportedLibraries
|
|
ImportedLibraries returns the paths of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.
(*File) ImportedSymbols
|
|
ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time.
(*File) Section
|
|
Section returns the first section with the given name, or nil if no such section exists.
(*File) Segment
|
|
Segment returns the first Segment with the given name, or nil if no such segment exists.
type FileHeader
|
|
A FileHeader represents a Mach-O file header.
type FormatError
|
|
FormatError is returned by some operations if the data does not have the correct format for an object file.
(*FormatError) Error
|
|
type Load
|
|
A Load represents any Mach-O load command.
type LoadBytes
|
|
A LoadBytes is the uninterpreted bytes of a Mach-O load command.
(LoadBytes) Raw
|
|
type LoadCmd
|
|
A LoadCmd is a Mach-O load command.
|
|
(LoadCmd) GoString
|
|
(LoadCmd) String
|
|
type Nlist32
|
|
An Nlist32 is a Mach-O 32-bit symbol table entry.
type Nlist64
|
|
An Nlist64 is a Mach-O 64-bit symbol table entry.
type Regs386
|
|
Regs386 is the Mach-O 386 register structure.
type RegsAMD64
|
|
RegsAMD64 is the Mach-O AMD64 register structure.
type Reloc <- go1.10
|
|
A Reloc represents a Mach-O relocation.
type RelocTypeARM <- go1.10
|
|
(RelocTypeARM) GoString <- go1.10
|
|
(RelocTypeARM) String <- go1.10
|
|
type RelocTypeARM64 <- go1.10
|
|
(RelocTypeARM64) GoString <- go1.10
|
|
(RelocTypeARM64) String <- go1.10
|
|
type RelocTypeGeneric <- go1.10
|
|
(RelocTypeGeneric) GoString <- go1.10
|
|
(RelocTypeGeneric) String <- go1.10
|
|
type RelocTypeX86_64 <- go1.10
|
|
(RelocTypeX86_64) GoString <- go1.10
|
|
(RelocTypeX86_64) String <- go1.10
|
|
type Rpath <- go1.10
|
|
A Rpath represents a Mach-O rpath command.
type RpathCmd <- go1.10
|
|
A RpathCmd is a Mach-O rpath command.
type Section
|
|
(*Section) Data
|
|
Data reads and returns the contents of the Mach-O section.
(*Section) Open
|
|
Open returns a new ReadSeeker reading the Mach-O section.
type Section32
|
|
A Section32 is a 32-bit Mach-O section header.
type Section64
|
|
A Section64 is a 64-bit Mach-O section header.
type SectionHeader
|
|
type Segment
|
|
A Segment represents a Mach-O 32-bit or 64-bit load segment command.
(*Segment) Data
|
|
Data reads and returns the contents of the segment.
(*Segment) Open
|
|
Open returns a new ReadSeeker reading the segment.
type Segment32
|
|
A Segment32 is a 32-bit Mach-O segment load command.
type Segment64
|
|
A Segment64 is a 64-bit Mach-O segment load command.
type SegmentHeader
|
|
A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment command.
type Symbol
|
|
A Symbol is a Mach-O 32-bit or 64-bit symbol table entry.
type Symtab
|
|
A Symtab represents a Mach-O symbol table command.
type SymtabCmd
|
|
A SymtabCmd is a Mach-O symbol table command.
type Thread
|
|
A Thread is a Mach-O thread state command.
type Type
|
|
A Type is the Mach-O file type, e.g. an object file, executable, or dynamic library.
|
|
(Type) GoString <- go1.10
|
|
(Type) String <- go1.10
|
|
6.6 - pe
pe
https://pkg.go.dev/debug/pe@go1.20.1
Package pe implements access to PE (Microsoft Windows Portable Executable) files.
Security
This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.
常量
|
|
|
|
IMAGE_DIRECTORY_ENTRY constants
|
|
Values of IMAGE_FILE_HEADER.Characteristics. These can be combined together.
|
|
OptionalHeader64.Subsystem and OptionalHeader32.Subsystem values.
|
|
OptionalHeader64.DllCharacteristics and OptionalHeader32.DllCharacteristics values. These can be combined together.
|
|
Section characteristics flags.
|
|
These constants make up the possible values for the ‘Selection’ field in an AuxFormat5.
|
|
变量
This section is empty.
函数
This section is empty.
类型
type COFFSymbol <- go1.1
|
|
COFFSymbol represents single COFF symbol table record.
(*COFFSymbol) FullName <- go1.8
|
|
FullName finds real name of symbol sym. Normally name is stored in sym.Name, but if it is longer then 8 characters, it is stored in COFF string table st instead.
type COFFSymbolAuxFormat5 <- go1.19
|
|
COFFSymbolAuxFormat5 describes the expected form of an aux symbol attached to a section definition symbol. The PE format defines a number of different aux symbol formats: format 1 for function definitions, format 2 for .be and .ef symbols, and so on. Format 5 holds extra info associated with a section definition, including number of relocations + line numbers, as well as COMDAT info. See https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-format-5-section-definitions for more on what’s going on here.
type DataDirectory <- go1.3
|
|
type File
|
|
A File represents an open PE file.
func NewFile
|
|
NewFile creates a new File for accessing a PE binary in an underlying reader.
func Open
|
|
Open opens the named file using os.Open and prepares it for use as a PE binary.
(*File) COFFSymbolReadSectionDefAux <- go1.19
|
|
COFFSymbolReadSectionDefAux returns a blob of axiliary information (including COMDAT info) for a section definition symbol. Here ‘idx’ is the index of a section symbol in the main COFFSymbol array for the File. Return value is a pointer to the appropriate aux symbol struct. For more info, see:
auxiliary symbols: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-symbol-records COMDAT sections: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#comdat-sections-object-only auxiliary info for section definitions: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-format-5-section-definitions
(*File) Close
|
|
Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.
(*File) DWARF
|
|
(*File) ImportedLibraries
|
|
ImportedLibraries returns the names of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.
(*File) ImportedSymbols
|
|
ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time. It does not return weak symbols.
(*File) Section
|
|
Section returns the first section with the given name, or nil if no such section exists.
type FileHeader
|
|
type FormatError
|
|
FormatError is unused. The type is retained for compatibility.
(*FormatError) Error
|
|
type ImportDirectory
|
|
type OptionalHeader32 <- go1.3
|
|
type OptionalHeader64 <- go1.3
|
|
type Reloc <- go1.8
|
|
Reloc represents a PE COFF relocation. Each section contains its own relocation list.
type Section
|
|
Section provides access to PE COFF section.
(*Section) Data
|
|
Data reads and returns the contents of the PE section s.
(*Section) Open
|
|
Open returns a new ReadSeeker reading the PE section s.
type SectionHeader
|
|
SectionHeader is similar to SectionHeader32 with Name field replaced by Go string.
type SectionHeader32
|
|
SectionHeader32 represents real PE COFF section header.
type StringTable <- go1.8
|
|
StringTable is a COFF string table.
(StringTable) String <- go1.8
|
|
String extracts string from COFF string table st at offset start.
type Symbol <- go1.1
|
|
Symbol is similar to COFFSymbol with Name field replaced by Go string. Symbol also does not have NumberOfAuxSymbols.
6.7 - plan9obj
plan9obj
https://pkg.go.dev/debug/plan9obj@go1.20.1
Package plan9obj implements access to Plan 9 a.out object files.
Security
This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.
常量
|
|
变量
|
|
ErrNoSymbols is returned by File.Symbols if there is no such section in the File.
函数
This section is empty.
类型
type File
|
|
A File represents an open Plan 9 a.out file.
func NewFile
|
|
NewFile creates a new File for accessing a Plan 9 binary in an underlying reader. The Plan 9 binary is expected to start at position 0 in the ReaderAt.
func Open
|
|
Open opens the named file using os.Open and prepares it for use as a Plan 9 a.out binary.
(*File) Close
|
|
Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.
(*File) Section
|
|
Section returns a section with the given name, or nil if no such section exists.
(*File) Symbols
|
|
Symbols returns the symbol table for f.
type FileHeader
|
|
A FileHeader represents a Plan 9 a.out file header.
type Section
|
|
A Section represents a single section in a Plan 9 a.out file.
(*Section) Data
|
|
Data reads and returns the contents of the Plan 9 a.out section.
(*Section) Open
|
|
Open returns a new ReadSeeker reading the Plan 9 a.out section.
type SectionHeader
|
|
A SectionHeader represents a single Plan 9 a.out section header. This structure doesn’t exist on-disk, but eases navigation through the object file.
type Sym
|
|
A Symbol represents an entry in a Plan 9 a.out symbol table section.
7 - encoding
7.1 - ascii85
ascii85
https://pkg.go.dev/encoding/ascii85@go1.20.1
Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobe’s PostScript and PDF document formats.
常量
This section is empty.
变量
This section is empty.
函数
func Decode
|
|
Decode decodes src into dst, returning both the number of bytes written to dst and the number consumed from src. If src contains invalid ascii85 data, Decode will return the number of bytes successfully written and a CorruptInputError. Decode ignores space and control characters in src. Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Decode expects these to have been stripped by the caller.
If flush is true, Decode assumes that src represents the end of the input stream and processes it completely rather than wait for the completion of another 32-bit block.
NewDecoder wraps an io.Reader interface around Decode.
func Encode
|
|
Encode encodes src into at most MaxEncodedLen(len(src)) bytes of dst, returning the actual number of bytes written.
The encoding handles 4-byte chunks, using a special encoding for the last fragment, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder() instead.
Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Encode does not add these.
func MaxEncodedLen
|
|
MaxEncodedLen returns the maximum length of an encoding of n source bytes.
func NewDecoder
|
|
NewDecoder constructs a new ascii85 stream decoder.
func NewEncoder
|
|
NewEncoder returns a new ascii85 stream encoder. Data written to the returned writer will be encoded and then written to w. Ascii85 encodings operate in 32-bit blocks; when finished writing, the caller must Close the returned encoder to flush any trailing partial block.
类型
type CorruptInputError
|
|
(CorruptInputError) Error
|
|
7.2 - asn1
asn1
https://pkg.go.dev/encoding/asn1@go1.20.1
Package asn1 implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.
See also “A Layman’s Guide to a Subset of ASN.1, BER, and DER,” http://luca.ntop.org/Teaching/Appunti/asn1.html.
常量
|
|
ASN.1 tags represent the type of the following object.
|
|
ASN.1 class types represent the namespace of the tag.
变量
|
|
NullBytes contains bytes representing the DER-encoded ASN.1 NULL type.
|
|
NullRawValue is a RawValue with its Tag set to the ASN.1 NULL type tag (5).
函数
func Marshal
|
|
Marshal returns the ASN.1 encoding of val.
In addition to the struct tags recognised by Unmarshal, the following can be used:
ia5: causes strings to be marshaled as ASN.1, IA5String values
omitempty: causes empty slices to be skipped
printable: causes strings to be marshaled as ASN.1, PrintableString values
utf8: causes strings to be marshaled as ASN.1, UTF8String values
utc: causes time.Time to be marshaled as ASN.1, UTCTime values
generalized: causes time.Time to be marshaled as ASN.1, GeneralizedTime values
func MarshalWithParams <- go1.10
|
|
MarshalWithParams allows field parameters to be specified for the top-level element. The form of the params is the same as the field tags.
func Unmarshal
|
|
Unmarshal parses the DER-encoded ASN.1 data structure b and uses the reflect package to fill in an arbitrary value pointed at by val. Because Unmarshal uses the reflect package, the structs being written to must use upper case field names. If val is nil or not a pointer, Unmarshal returns an error.
After parsing b, any bytes that were leftover and not used to fill val will be returned in rest. When parsing a SEQUENCE into a struct, any trailing elements of the SEQUENCE that do not have matching fields in val will not be included in rest, as these are considered valid elements of the SEQUENCE and not trailing data.
An ASN.1 INTEGER can be written to an int, int32, int64, or *big.Int (from the math/big package). If the encoded value does not fit in the Go type, Unmarshal returns a parse error.
An ASN.1 BIT STRING can be written to a BitString.
An ASN.1 OCTET STRING can be written to a []byte.
An ASN.1 OBJECT IDENTIFIER can be written to an ObjectIdentifier.
An ASN.1 ENUMERATED can be written to an Enumerated.
An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time.
An ASN.1 PrintableString, IA5String, or NumericString can be written to a string.
Any of the above ASN.1 values can be written to an interface{}. The value stored in the interface has the corresponding Go type. For integers, that type is int64.
An ASN.1 SEQUENCE OF x or SET OF x can be written to a slice if an x can be written to the slice’s element type.
An ASN.1 SEQUENCE or SET can be written to a struct if each of the elements in the sequence can be written to the corresponding element in the struct.
The following tags on struct fields have special meaning to Unmarshal:
application specifies that an APPLICATION tag is used
private specifies that a PRIVATE tag is used
default:x sets the default value for optional integer fields (only used if optional is also present)
explicit specifies that an additional, explicit tag wraps the implicit one
optional marks the field as ASN.1 OPTIONAL
set causes a SET, rather than a SEQUENCE type to be expected
tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC
When decoding an ASN.1 value with an IMPLICIT tag into a string field, Unmarshal will default to a PrintableString, which doesn’t support characters such as ‘@’ and ‘&’. To force other encodings, use the following tags:
ia5 causes strings to be unmarshaled as ASN.1 IA5String values
numeric causes strings to be unmarshaled as ASN.1 NumericString values
utf8 causes strings to be unmarshaled as ASN.1 UTF8String values
If the type of the first field of a structure is RawContent then the raw ASN1 contents of the struct will be stored in it.
If the name of a slice type ends with “SET” then it’s treated as if the “set” tag was set on it. This results in interpreting the type as a SET OF x rather than a SEQUENCE OF x. This can be used with nested slices where a struct tag cannot be given.
Other ASN.1 types are not supported; if it encounters them, Unmarshal returns a parse error.
func UnmarshalWithParams
|
|
UnmarshalWithParams allows field parameters to be specified for the top-level element. The form of the params is the same as the field tags.
类型
type BitString
|
|
BitString is the structure to use when you want an ASN.1 BIT STRING type. A bit string is padded up to the nearest byte in memory and the number of valid bits is recorded. Padding bits will be zero.
(BitString) At
|
|
At returns the bit at the given index. If the index is out of range it returns 0.
(BitString) RightAlign
|
|
RightAlign returns a slice where the padding bits are at the beginning. The slice may share memory with the BitString.
type Enumerated
|
|
An Enumerated is represented as a plain int.
type Flag
|
|
A Flag accepts any data and is set to true if present.
type ObjectIdentifier
|
|
An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.
(ObjectIdentifier) Equal
|
|
Equal reports whether oi and other represent the same identifier.
(ObjectIdentifier) String <- go1.3
|
|
type RawContent
|
|
RawContent is used to signal that the undecoded, DER data needs to be preserved for a struct. To use it, the first field of the struct must have this type. It’s an error for any of the other fields to have this type.
type RawValue
|
|
A RawValue represents an undecoded ASN.1 object.
type StructuralError
|
|
A StructuralError suggests that the ASN.1 data is valid, but the Go type which is receiving it doesn’t match.
(StructuralError) Error
|
|
type SyntaxError
|
|
A SyntaxError suggests that the ASN.1 data is invalid.
(SyntaxError) Error
|
|
7.3 - base32
base32
https://pkg.go.dev/encoding/base32@go1.20.1
Package base32 implements base32 encoding as specified by RFC 4648.
常量
|
|
变量
|
|
HexEncoding is the “Extended Hex Alphabet” defined in RFC 4648. It is typically used in DNS.
|
|
StdEncoding is the standard base32 encoding, as defined in RFC 4648.
函数
func NewDecoder
|
|
NewDecoder constructs a new base32 stream decoder.
func NewEncoder
|
|
NewEncoder returns a new base32 stream encoder. Data written to the returned writer will be encoded using enc and then written to w. Base32 encodings operate in 5-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.
Example
|
|
类型
type CorruptInputError
|
|
(CorruptInputError) Error
|
|
type Encoding
|
|
An Encoding is a radix 32 encoding/decoding scheme, defined by a 32-character alphabet. The most common is the “base32” encoding introduced for SASL GSSAPI and standardized in RFC 4648. The alternate “base32hex” encoding is used in DNSSEC.
func NewEncoding
|
|
NewEncoding returns a new Encoding defined by the given alphabet, which must be a 32-byte string.
(*Encoding) Decode
|
|
Decode decodes src using the encoding enc. It writes at most DecodedLen(len(src)) bytes to dst and returns the number of bytes written. If src contains invalid base32 data, it will return the number of bytes successfully written and CorruptInputError. New line characters (\r and \n) are ignored.
Example
|
|
(*Encoding) DecodeString
|
|
DecodeString returns the bytes represented by the base32 string s.
Example
|
|
(*Encoding) DecodedLen
|
|
DecodedLen returns the maximum length in bytes of the decoded data corresponding to n bytes of base32-encoded data.
(*Encoding) Encode
|
|
Encode encodes src using the encoding enc, writing EncodedLen(len(src)) bytes to dst.
The encoding pads the output to a multiple of 8 bytes, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder() instead.
Example
|
|
(*Encoding) EncodeToString
|
|
EncodeToString returns the base32 encoding of src.
Example
|
|
(*Encoding) EncodedLen
|
|
EncodedLen returns the length in bytes of the base32 encoding of an input buffer of length n.
(Encoding) WithPadding <- go1.9
|
|
WithPadding creates a new encoding identical to enc except with a specified padding character, or NoPadding to disable padding. The padding character must not be ‘\r’ or ‘\n’, must not be contained in the encoding’s alphabet and must be a rune equal or below ‘\xff’.
7.4 - base64
base64
https://pkg.go.dev/encoding/base64@go1.20.1
Package base64 implements base64 encoding as specified by RFC 4648.
包 base64 实现了 RFC 4648 所规定的 base64 编码。
Example
|
|
常量
|
|
变量
|
|
RawStdEncoding is the standard raw, unpadded base64 encoding, as defined in RFC 4648 section 3.2. This is the same as StdEncoding but omits padding characters.
RawStdEncoding是标准的原始、无填充的base64编码,定义于RFC 4648第3.2节。这与StdEncoding相同,但省略了填充字符。
|
|
RawURLEncoding is the unpadded alternate base64 encoding defined in RFC 4648. It is typically used in URLs and file names. This is the same as URLEncoding but omits padding characters.
RawURLEncoding是RFC 4648中定义的无填充的另一种base64编码。它通常在URL和文件名中使用。这与URLEncoding相同,但省略了填充字符。
|
|
StdEncoding is the standard base64 encoding, as defined in RFC 4648.
StdEncoding是标准的base64编码,如RFC 4648所定义。
|
|
URLEncoding is the alternate base64 encoding defined in RFC 4648. It is typically used in URLs and file names.
URLEncoding是RFC 4648中定义的备用base64编码。它通常在URL和文件名中使用。
函数
func NewDecoder
|
|
NewDecoder constructs a new base64 stream decoder.
NewDecoder构建一个新的base64流解码器。
func NewEncoder
|
|
NewEncoder returns a new base64 stream encoder. Data written to the returned writer will be encoded using enc and then written to w. Base64 encodings operate in 4-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.
NewEncoder返回一个新的base64流编码器。写入返回的写入器的数据将使用enc进行编码,然后写入w。Base64编码以4字节的块进行操作;当写完后,调用者必须关闭返回的编码器以冲刷任何部分写入的块。
Example
|
|
类型
type CorruptInputError
|
|
(CorruptInputError) Error
|
|
type Encoding
|
|
An Encoding is a radix 64 encoding/decoding scheme, defined by a 64-character alphabet. The most common encoding is the “base64” encoding defined in RFC 4648 and used in MIME (RFC 2045) and PEM (RFC 1421). RFC 4648 also defines an alternate encoding, which is the standard encoding with - and _ substituted for + and /.
编码是一个弧度为64的编码/解码方案,由一个64字符的字母表定义。最常见的编码是RFC 4648中定义的 “base64 “编码,在MIME(RFC 2045)和PEM(RFC 1421)中使用。RFC 4648还定义了一个备用编码,即用-和_代替+和/的标准编码。
func NewEncoding
|
|
NewEncoding returns a new padded Encoding defined by the given alphabet, which must be a 64-byte string that does not contain the padding character or CR / LF (’\r’, ‘\n’). The resulting Encoding uses the default padding character (’=’), which may be changed or disabled via WithPadding.
NewEncoding返回一个由给定字母定义的新的填充编码,它必须是一个64字节的字符串,不包含填充字符或CR / LF(’\r’, ‘\n’)。产生的Encoding使用默认的padding字符(’=’),可以通过WithPadding改变或禁用。
(*Encoding) Decode
|
|
Decode decodes src using the encoding enc. It writes at most DecodedLen(len(src)) bytes to dst and returns the number of bytes written. If src contains invalid base64 data, it will return the number of bytes successfully written and CorruptInputError. New line characters (\r and \n) are ignored.
Decode使用enc编码对src进行解码。它最多向dst写入DecodedLen(len(src))字节,并返回写入的字节数。如果src包含无效的base64数据,它将返回成功写入的字节数和CorruptInputError。新行字符(\r 和 \n)被忽略。
Example
|
|
(*Encoding) DecodeString
|
|
DecodeString returns the bytes represented by the base64 string s.
DecodeString返回base64字符串s所代表的字节。
Example
|
|
(*Encoding) DecodedLen
|
|
DecodedLen returns the maximum length in bytes of the decoded data corresponding to n bytes of base64-encoded data.
DecodedLen返回对应于base64编码的n个字节的解码数据的最大长度(字节)。
(*Encoding) Encode
|
|
Encode encodes src using the encoding enc, writing EncodedLen(len(src)) bytes to dst.
Encode使用enc编码对src进行编码,向dst写入EncodedLen(len(src))字节。
The encoding pads the output to a multiple of 4 bytes, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder() instead.
编码将输出填充为4字节的倍数,所以Encode不适合用于大数据流的单个块。请使用NewEncoder()代替。
Example
|
|
(*Encoding) EncodeToString
|
|
EncodeToString returns the base64 encoding of src.
EncodeToString返回src的base64编码。
Example
|
|
(*Encoding) EncodedLen
|
|
EncodedLen returns the length in bytes of the base64 encoding of an input buffer of length n.
EncodedLen返回一个长度为n的输入缓冲区的base64编码的字节长度。
(Encoding) Strict <- go1.8
|
|
Strict creates a new encoding identical to enc except with strict decoding enabled. In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5.
严格创建一个与enc相同的新编码,只是启用了严格解码。在这种模式下,解码器要求尾部填充位为零,如RFC 4648第3.5节所述。
Note that the input is still malleable, as new line characters (CR and LF) are still ignored.
注意,输入仍然是可塑的,因为新的行字符(CR和LF)仍然被忽略。
(Encoding) WithPadding <- go1.5
|
|
WithPadding creates a new encoding identical to enc except with a specified padding character, or NoPadding to disable padding. The padding character must not be ‘\r’ or ‘\n’, must not be contained in the encoding’s alphabet and must be a rune equal or below ‘\xff’.
WithPadding创建一个与enc相同的新编码,除了指定的padding字符,或者用NoPadding来禁用padding。填充字符不能是’\r’或’\n’,不能包含在编码的字母表中,必须是等于或低于’\xff’的符文。
7.5 - binary
binary
https://pkg.go.dev/encoding/binary@go1.20.1
Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.
Numbers are translated by reading and writing fixed-size values. A fixed-size value is either a fixed-size arithmetic type (bool, int8, uint8, int16, float32, complex64, …) or an array or struct containing only fixed-size values.
The varint functions encode and decode single integer values using a variable-length encoding; smaller values require fewer bytes. For a specification, see https://developers.google.com/protocol-buffers/docs/encoding.
This package favors simplicity over efficiency. Clients that require high-performance serialization, especially for large data structures, should look at more advanced solutions such as the encoding/gob package or protocol buffers.
常量
|
|
MaxVarintLenN is the maximum length of a varint-encoded N-bit integer.
变量
|
|
BigEndian is the big-endian implementation of ByteOrder and AppendByteOrder.
|
|
LittleEndian is the little-endian implementation of ByteOrder and AppendByteOrder.
函数
func AppendUvarint <- go1.19
|
|
AppendUvarint appends the varint-encoded form of x, as generated by PutUvarint, to buf and returns the extended buffer.
func AppendVarint <- go1.19
|
|
AppendVarint appends the varint-encoded form of x, as generated by PutVarint, to buf and returns the extended buffer.
func PutUvarint
|
|
PutUvarint encodes a uint64 into buf and returns the number of bytes written. If the buffer is too small, PutUvarint will panic.
Example
|
|
func PutVarint
|
|
PutVarint encodes an int64 into buf and returns the number of bytes written. If the buffer is too small, PutVarint will panic.
Example
|
|
func Read
|
|
Read reads structured binary data from r into data. Data must be a pointer to a fixed-size value or a slice of fixed-size values. Bytes read from r are decoded using the specified byte order and written to successive fields of the data. When decoding boolean values, a zero byte is decoded as false, and any other non-zero byte is decoded as true. When reading into structs, the field data for fields with blank (_) field names is skipped; i.e., blank field names may be used for padding. When reading into a struct, all non-blank fields must be exported or Read may panic.
The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, Read returns ErrUnexpectedEOF.
Example
|
|
Example
|
|
func ReadUvarint
|
|
ReadUvarint reads an encoded unsigned integer from r and returns it as a uint64. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadUvarint returns io.ErrUnexpectedEOF.
func ReadVarint
|
|
ReadVarint reads an encoded signed integer from r and returns it as an int64. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadVarint returns io.ErrUnexpectedEOF.
func Size
|
|
Size returns how many bytes Write would generate to encode the value v, which must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. If v is neither of these, Size returns -1.
func Uvarint
|
|
Uvarint decodes a uint64 from buf and returns that value and the number of bytes read (> 0). If an error occurred, the value is 0 and the number of bytes n is <= 0 meaning:
n == 0: buf too small
n < 0: value larger than 64 bits (overflow)
and -n is the number of bytes read
Example
|
|
func Varint
|
|
Varint decodes an int64 from buf and returns that value and the number of bytes read (> 0). If an error occurred, the value is 0 and the number of bytes n is <= 0 with the following meaning:
n == 0: buf too small
n < 0: value larger than 64 bits (overflow)
and -n is the number of bytes read
Example
|
|
func Write
|
|
Write writes the binary representation of data into w. Data must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. Boolean values encode as one byte: 1 for true, and 0 for false. Bytes written to w are encoded using the specified byte order and read from successive fields of the data. When writing structs, zero values are written for fields with blank (_) field names.
Example
|
|
Example
|
|
类型
type AppendByteOrder <- go1.19
|
|
AppendByteOrder specifies how to append 16-, 32-, or 64-bit unsigned integers into a byte slice.
type ByteOrder
|
|
A ByteOrder specifies how to convert byte slices into 16-, 32-, or 64-bit unsigned integers.
Example
|
|
7.6 - csv
csv
https://pkg.go.dev/encoding/csv@go1.20.1
Package csv reads and writes comma-separated values (CSV) files. There are many kinds of CSV files; this package supports the format described in RFC 4180.
csv包读取和写入逗号分隔的值(CSV)文件。有许多种CSV文件;这个包支持RFC 4180中描述的格式。
A csv file contains zero or more records of one or more fields per record. Each record is separated by the newline character. The final record may optionally be followed by a newline character.
一个csv文件包含零个或多个记录,每个记录有一个或多个字段。每条记录由换行符分隔。最后一条记录后面可以选择换行符。
field1,field2,field3
White space is considered part of a field.
白色空间被认为是字段的一部分。
Carriage returns before newline characters are silently removed.
换行符之前的回车符会被默默地删除。
Blank lines are ignored. A line with only whitespace characters (excluding the ending newline character) is not considered a blank line.
空白行被忽略。只有空白字符的行(不包括结尾的换行字符)不被视为空行。
Fields which start and stop with the quote character " are called quoted-fields. The beginning and ending quote are not part of the field.
以引号字符"“开始和结束的字段被称为引号字段。开始和结束的引号不是字段的一部分。
The source:
来源:
normal string,"quoted-field"
results in the fields
的结果是字段
{`normal string`, `quoted-field`}
Within a quoted-field a quote character followed by a second quote character is considered a single quote.
在一个带引号的字段内,一个引号字符后面的第二个引号字符被认为是一个单引号。
"the ""word"" is true","a ""quoted-field"""
results in
结果是
{`the "word" is true`, `a "quoted-field"`}
Newlines and commas may be included in a quoted-field
换行符和逗号可以包含在一个引号字段中。
"Multi-line
field","comma is ,"
results in
结果是
{`Multi-line
field`, `comma is ,`}
常量
This section is empty.
变量
|
|
These are the errors that can be returned in ParseError.Err.
这些是可以在ParseError.Err中返回的错误。
函数
This section is empty.
类型
type ParseError
|
|
A ParseError is returned for parsing errors. Line numbers are 1-indexed and columns are 0-indexed.
对于解析错误会返回一个ParseError。行号是1-索引的,列是0-索引的。
(*ParseError) Error
|
|
(*ParseError) Unwrap <- go1.13
|
|
type Reader
|
|
A Reader reads records from a CSV-encoded file.
Reader 从一个CSV编码的文件中读取记录。
As returned by NewReader, a Reader expects input conforming to RFC 4180. The exported fields can be changed to customize the details before the first call to Read or ReadAll.
正如NewReader所返回的那样,Reader期望输入的内容符合RFC 4180的规定。在第一次调用Read或ReadAll之前,导出的字段可以被改变以定制细节。
The Reader converts all \r\n sequences in its input to plain \n, including in multiline field values, so that the returned data does not depend on which line-ending convention an input file uses.
Reader 将其输入中的所有\r\n序列转换为普通的\n,包括在多行字段值中,因此返回的数据不依赖于输入文件使用的行结束惯例。
Example
|
|
Example
|
|
func NewReader
|
|
NewReader returns a new Reader that reads from r.
NewReader返回一个新的阅读器,从r中读取数据。
(*Reader) FieldPos <- go1.17
|
|
FieldPos returns the line and column corresponding to the start of the field with the given index in the slice most recently returned by Read. Numbering of lines and columns starts at 1; columns are counted in bytes, not runes.
FieldPos返回对应于最近由Read返回的片断中具有给定索引的字段开始的行和列。行和列的编号从1开始;列的计数单位是字节,而不是符码。
If this is called with an out-of-bounds index, it panics.
如果在调用这个函数时,索引超出了范围,它就会惊慌失措。
(*Reader) InputOffset <- go1.19
|
|
InputOffset returns the input stream byte offset of the current reader position. The offset gives the location of the end of the most recently read row and the beginning of the next row.
InputOffset返回当前阅读器位置的输入流字节偏移。这个偏移量给出了最近读取的行的结束和下一行的开始的位置。
(*Reader) Read
|
|
Read reads one record (a slice of fields) from r. If the record has an unexpected number of fields, Read returns the record along with the error ErrFieldCount. Except for that case, Read always returns either a non-nil record or a non-nil error, but not both. If there is no data left to be read, Read returns nil, io.EOF. If ReuseRecord is true, the returned slice may be shared between multiple calls to Read.
如果记录有一个意外的字段数,Read会返回记录和错误ErrFieldCount。除了这种情况,Read总是返回一个非空的记录或一个非空的错误,但不会同时返回。如果没有数据可读,Read返回nil,即io.EOF。如果ReuseRecord为真,返回的片断可以在多次调用Read时共享。
(*Reader) ReadAll
|
|
ReadAll reads all the remaining records from r. Each record is a slice of fields. A successful call returns err == nil, not err == io.EOF. Because ReadAll is defined to read until EOF, it does not treat end of file as an error to be reported.
ReadAll从r读取所有剩余的记录。一个成功的调用返回err == nil,而不是err == io.EOF。因为ReadAll被定义为读到EOF为止,它不把文件结束作为一个错误来报告。
Example
|
|
type Writer
|
|
A Writer writes records using CSV encoding.
Writer使用CSV编码来写记录。
As returned by NewWriter, a Writer writes records terminated by a newline and uses ‘,’ as the field delimiter. The exported fields can be changed to customize the details before the first call to Write or WriteAll.
正如NewWriter所返回的那样,Writer写入的记录以换行方式结束,并使用’,‘作为字段分隔符。在第一次调用Write或WriteAll之前,可以改变导出的字段以定制细节。
Comma is the field delimiter.
逗号是字段分隔符。
If UseCRLF is true, the Writer ends each output line with \r\n instead of \n.
如果UseCRLF为真,Writer会以\r\n而不是\n结束每个输出行。
The writes of individual records are buffered. After all data has been written, the client should call the Flush method to guarantee all data has been forwarded to the underlying io.Writer. Any errors that occurred should be checked by calling the Error method.
单个记录的写入是缓冲的。在所有数据被写入后,客户端应该调用Flush方法以保证所有数据都被转发到底层的io.Writer。任何发生的错误都应该通过调用Error方法来检查。
Example
|
|
func NewWriter
|
|
NewWriter returns a new Writer that writes to w.
NewWriter返回一个新的写入w的Writer。
(*Writer) Error <- go1.1
|
|
Error reports any error that has occurred during a previous Write or Flush.
Error报告在之前的写或刷新过程中发生的任何错误。
(*Writer) Flush
|
|
Flush writes any buffered data to the underlying io.Writer. To check if an error occurred during the Flush, call Error.
Flush将任何缓冲的数据写入底层的io.Writer。要检查在Flush过程中是否有错误发生,请调用Error。
(*Writer) Write
|
|
Write writes a single CSV record to w along with any necessary quoting. A record is a slice of strings with each string being one field. Writes are buffered, so Flush must eventually be called to ensure that the record is written to the underlying io.Writer.
Write将一条CSV记录和任何必要的引号一起写到w中。一个记录是一个字符串的切片,每个字符串是一个字段。写入是缓冲的,所以最终必须调用Flush以确保记录被写入底层的io.Writer。
(*Writer) WriteAll
|
|
WriteAll writes multiple CSV records to w using Write and then calls Flush, returning any error from the Flush.
WriteAll使用Write将多个CSV记录写入w,然后调用Flush,返回Flush的任何错误。
|
|
7.7 - encoding
encoding
https://pkg.go.dev/encoding@go1.20.1
Package encoding defines interfaces shared by other packages that convert data to and from byte-level and textual representations. Packages that check for these interfaces include encoding/gob, encoding/json, and encoding/xml. As a result, implementing an interface once can make a type useful in multiple encodings. Standard types that implement these interfaces include time.Time and net.IP. The interfaces come in pairs that produce and consume encoded data.
常量
This section is empty.
变量
This section is empty.
函数
This section is empty.
类型
type BinaryMarshaler
|
|
BinaryMarshaler is the interface implemented by an object that can marshal itself into a binary form.
MarshalBinary encodes the receiver into a binary form and returns the result.
type BinaryUnmarshaler
|
|
BinaryUnmarshaler is the interface implemented by an object that can unmarshal a binary representation of itself.
UnmarshalBinary must be able to decode the form generated by MarshalBinary. UnmarshalBinary must copy the data if it wishes to retain the data after returning.
type TextMarshaler
|
|
TextMarshaler is the interface implemented by an object that can marshal itself into a textual form.
MarshalText encodes the receiver into UTF-8-encoded text and returns the result.
type TextUnmarshaler
|
|
TextUnmarshaler is the interface implemented by an object that can unmarshal a textual representation of itself.
UnmarshalText must be able to decode the form generated by MarshalText. UnmarshalText must copy the text if it wishes to retain the text after returning.
7.8 - gob
gob
https://pkg.go.dev/encoding/gob@go1.20.1
Package gob manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver). A typical use is transporting arguments and results of remote procedure calls (RPCs) such as those provided by package “net/rpc”.
The implementation compiles a custom codec for each data type in the stream and is most efficient when a single Encoder is used to transmit a stream of values, amortizing the cost of compilation.
Basics
A stream of gobs is self-describing. Each data item in the stream is preceded by a specification of its type, expressed in terms of a small set of predefined types. Pointers are not transmitted, but the things they point to are transmitted; that is, the values are flattened. Nil pointers are not permitted, as they have no value. Recursive types work fine, but recursive values (data with cycles) are problematic. This may change.
To use gobs, create an Encoder and present it with a series of data items as values or addresses that can be dereferenced to values. The Encoder makes sure all type information is sent before it is needed. At the receive side, a Decoder retrieves values from the encoded stream and unpacks them into local variables.
类型
The source and destination values/types need not correspond exactly. For structs, fields (identified by name) that are in the source but absent from the receiving variable will be ignored. Fields that are in the receiving variable but missing from the transmitted type or value will be ignored in the destination. If a field with the same name is present in both, their types must be compatible. Both the receiver and transmitter will do all necessary indirection and dereferencing to convert between gobs and actual Go values. For instance, a gob type that is schematically,
struct { A, B int }
can be sent from or received into any of these Go types:
struct { A, B int } // the same
*struct { A, B int } // extra indirection of the struct
struct { *A, **B int } // extra indirection of the fields
struct { A, B int64 } // different concrete value type; see below
It may also be received into any of these:
struct { A, B int } // the same
struct { B, A int } // ordering doesn't matter; matching is by name
struct { A, B, C int } // extra field (C) ignored
struct { B int } // missing field (A) ignored; data will be dropped
struct { B, C int } // missing field (A) ignored; extra field (C) ignored.
Attempting to receive into these types will draw a decode error:
struct { A int; B uint } // change of signedness for B
struct { A int; B float } // change of type for B
struct { } // no field names in common
struct { C, D int } // no field names in common
Integers are transmitted two ways: arbitrary precision signed integers or arbitrary precision unsigned integers. There is no int8, int16 etc. discrimination in the gob format; there are only signed and unsigned integers. As described below, the transmitter sends the value in a variable-length encoding; the receiver accepts the value and stores it in the destination variable. Floating-point numbers are always sent using IEEE-754 64-bit precision (see below).
Signed integers may be received into any signed integer variable: int, int16, etc.; unsigned integers may be received into any unsigned integer variable; and floating point values may be received into any floating point variable. However, the destination variable must be able to represent the value or the decode operation will fail.
Structs, arrays and slices are also supported. Structs encode and decode only exported fields. Strings and arrays of bytes are supported with a special, efficient representation (see below). When a slice is decoded, if the existing slice has capacity the slice will be extended in place; if not, a new array is allocated. Regardless, the length of the resulting slice reports the number of elements decoded.
In general, if allocation is required, the decoder will allocate memory. If not, it will update the destination variables with values read from the stream. It does not initialize them first, so if the destination is a compound value such as a map, struct, or slice, the decoded values will be merged elementwise into the existing variables.
Functions and channels will not be sent in a gob. Attempting to encode such a value at the top level will fail. A struct field of chan or func type is treated exactly like an unexported field and is ignored.
Gob can encode a value of any type implementing the GobEncoder or encoding.BinaryMarshaler interfaces by calling the corresponding method, in that order of preference.
Gob can decode a value of any type implementing the GobDecoder or encoding.BinaryUnmarshaler interfaces by calling the corresponding method, again in that order of preference.
Encoding Details
This section documents the encoding, details that are not important for most users. Details are presented bottom-up.
An unsigned integer is sent one of two ways. If it is less than 128, it is sent as a byte with that value. Otherwise it is sent as a minimal-length big-endian (high byte first) byte stream holding the value, preceded by one byte holding the byte count, negated. Thus 0 is transmitted as (00), 7 is transmitted as (07) and 256 is transmitted as (FE 01 00).
A boolean is encoded within an unsigned integer: 0 for false, 1 for true.
A signed integer, i, is encoded within an unsigned integer, u. Within u, bits 1 upward contain the value; bit 0 says whether they should be complemented upon receipt. The encode algorithm looks like this:
|
|
The low bit is therefore analogous to a sign bit, but making it the complement bit instead guarantees that the largest negative integer is not a special case. For example, -129=^128=(^256»1) encodes as (FE 01 01).
Floating-point numbers are always sent as a representation of a float64 value. That value is converted to a uint64 using math.Float64bits. The uint64 is then byte-reversed and sent as a regular unsigned integer. The byte-reversal means the exponent and high-precision part of the mantissa go first. Since the low bits are often zero, this can save encoding bytes. For instance, 17.0 is encoded in only three bytes (FE 31 40).
Strings and slices of bytes are sent as an unsigned count followed by that many uninterpreted bytes of the value.
All other slices and arrays are sent as an unsigned count followed by that many elements using the standard gob encoding for their type, recursively.
Maps are sent as an unsigned count followed by that many key, element pairs. Empty but non-nil maps are sent, so if the receiver has not allocated one already, one will always be allocated on receipt unless the transmitted map is nil and not at the top level.
In slices and arrays, as well as maps, all elements, even zero-valued elements, are transmitted, even if all the elements are zero.
Structs are sent as a sequence of (field number, field value) pairs. The field value is sent using the standard gob encoding for its type, recursively. If a field has the zero value for its type (except for arrays; see above), it is omitted from the transmission. The field number is defined by the type of the encoded struct: the first field of the encoded type is field 0, the second is field 1, etc. When encoding a value, the field numbers are delta encoded for efficiency and the fields are always sent in order of increasing field number; the deltas are therefore unsigned. The initialization for the delta encoding sets the field number to -1, so an unsigned integer field 0 with value 7 is transmitted as unsigned delta = 1, unsigned value = 7 or (01 07). Finally, after all the fields have been sent a terminating mark denotes the end of the struct. That mark is a delta=0 value, which has representation (00).
Interface types are not checked for compatibility; all interface types are treated, for transmission, as members of a single “interface” type, analogous to int or []byte - in effect they’re all treated as interface{}. Interface values are transmitted as a string identifying the concrete type being sent (a name that must be pre-defined by calling Register), followed by a byte count of the length of the following data (so the value can be skipped if it cannot be stored), followed by the usual encoding of concrete (dynamic) value stored in the interface value. (A nil interface value is identified by the empty string and transmits no value.) Upon receipt, the decoder verifies that the unpacked concrete item satisfies the interface of the receiving variable.
If a value is passed to Encode and the type is not a struct (or pointer to struct, etc.), for simplicity of processing it is represented as a struct of one field. The only visible effect of this is to encode a zero byte after the value, just as after the last field of an encoded struct, so that the decode algorithm knows when the top-level value is complete.
The representation of types is described below. When a type is defined on a given connection between an Encoder and Decoder, it is assigned a signed integer type id. When Encoder.Encode(v) is called, it makes sure there is an id assigned for the type of v and all its elements and then it sends the pair (typeid, encoded-v) where typeid is the type id of the encoded type of v and encoded-v is the gob encoding of the value v.
To define a type, the encoder chooses an unused, positive type id and sends the pair (-type id, encoded-type) where encoded-type is the gob encoding of a wireType description, constructed from these types:
|
|
If there are nested type ids, the types for all inner type ids must be defined before the top-level type id is used to describe an encoded-v.
For simplicity in setup, the connection is defined to understand these types a priori, as well as the basic gob types int, uint, etc. Their ids are:
bool 1
int 2
uint 3
float 4
[]byte 5
string 6
complex 7
interface 8
// gap for reserved ids.
WireType 16
ArrayType 17
CommonType 18
SliceType 19
StructType 20
FieldType 21
// 22 is slice of fieldType.
MapType 23
Finally, each message created by a call to Encode is preceded by an encoded unsigned integer count of the number of bytes remaining in the message. After the initial type name, interface values are wrapped the same way; in effect, the interface value acts like a recursive invocation of Encode.
In summary, a gob stream looks like
(byteCount (-type id, encoding of a wireType)* (type id, encoding of a value))*
where * signifies zero or more repetitions and the type id of a value must be predefined or be defined before the value in the stream.
Compatibility: Any future changes to the package will endeavor to maintain compatibility with streams encoded using previous versions. That is, any released version of this package should be able to decode data written with any previously released version, subject to issues such as security fixes. See the Go compatibility document for background: https://golang.org/doc/go1compat
See “Gobs of data” for a design discussion of the gob wire format: https://blog.golang.org/gobs-of-data
Security
This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, the Decoder does only basic sanity checking on decoded input sizes, and its limits are not configurable. Care should be taken when decoding gob data from untrusted sources, which may consume significant resources.
Example
|
|
Example
|
|
Example
|
|
常量
This section is empty.
变量
This section is empty.
函数
func Register
|
|
Register records a type, identified by a value for that type, under its internal type name. That name will identify the concrete type of a value sent or received as an interface variable. Only types that will be transferred as implementations of interface values need to be registered. Expecting to be used only during initialization, it panics if the mapping between types and names is not a bijection.
func RegisterName
|
|
RegisterName is like Register but uses the provided name rather than the type’s default.
类型
type CommonType
|
|
CommonType holds elements of all types. It is a historical artifact, kept for binary compatibility and exported only for the benefit of the package’s encoding of type descriptors. It is not intended for direct use by clients.
type Decoder
|
|
A Decoder manages the receipt of type and data information read from the remote side of a connection. It is safe for concurrent use by multiple goroutines.
The Decoder does only basic sanity checking on decoded input sizes, and its limits are not configurable. Take caution when decoding gob data from untrusted sources.
func NewDecoder
|
|
NewDecoder returns a new decoder that reads from the io.Reader. If r does not also implement io.ByteReader, it will be wrapped in a bufio.Reader.
(*Decoder) Decode
|
|
Decode reads the next value from the input stream and stores it in the data represented by the empty interface value. If e is nil, the value will be discarded. Otherwise, the value underlying e must be a pointer to the correct type for the next data item received. If the input is at EOF, Decode returns io.EOF and does not modify e.
(*Decoder) DecodeValue
|
|
DecodeValue reads the next value from the input stream. If v is the zero reflect.Value (v.Kind() == Invalid), DecodeValue discards the value. Otherwise, it stores the value into v. In that case, v must represent a non-nil pointer to data or be an assignable reflect.Value (v.CanSet()) If the input is at EOF, DecodeValue returns io.EOF and does not modify v.
type Encoder
|
|
An Encoder manages the transmission of type and data information to the other side of a connection. It is safe for concurrent use by multiple goroutines.
func NewEncoder
|
|
NewEncoder returns a new encoder that will transmit on the io.Writer.
(*Encoder) Encode
|
|
Encode transmits the data item represented by the empty interface value, guaranteeing that all necessary type information has been transmitted first. Passing a nil pointer to Encoder will panic, as they cannot be transmitted by gob.
(*Encoder) EncodeValue
|
|
EncodeValue transmits the data item represented by the reflection value, guaranteeing that all necessary type information has been transmitted first. Passing a nil pointer to EncodeValue will panic, as they cannot be transmitted by gob.
type GobDecoder
|
|
GobDecoder is the interface describing data that provides its own routine for decoding transmitted values sent by a GobEncoder.
type GobEncoder
|
|
GobEncoder is the interface describing data that provides its own representation for encoding values for transmission to a GobDecoder. A type that implements GobEncoder and GobDecoder has complete control over the representation of its data and may therefore contain things such as private fields, channels, and functions, which are not usually transmissible in gob streams.
Note: Since gobs can be stored permanently, it is good design to guarantee the encoding used by a GobEncoder is stable as the software evolves. For instance, it might make sense for GobEncode to include a version number in the encoding.
7.9 - hex
hex
https://pkg.go.dev/encoding/hex@go1.20.1
Package hex implements hexadecimal encoding and decoding.
包hex实现了十六进制的编码和解码。
常量
This section is empty.
变量
|
|
ErrLength reports an attempt to decode an odd-length input using Decode or DecodeString. The stream-based Decoder returns io.ErrUnexpectedEOF instead of ErrLength.
ErrLength报告使用Decode或DecodeString解码一个奇长的输入的尝试。基于流的解码器返回io.ErrUnexpectedEOF而不是ErrLength。
函数
func Decode
|
|
Decode decodes src into DecodedLen(len(src)) bytes, returning the actual number of bytes written to dst.
Decode将src解码为DecodedLen(len(src))字节,返回写给dst的实际字节数。
Decode expects that src contains only hexadecimal characters and that src has even length. If the input is malformed, Decode returns the number of bytes decoded before the error.
解码期望src只包含十六进制的字符,并且src的长度是偶数。如果输入是畸形的,Decode会返回错误发生前的解码字节数。
Example
|
|
func DecodeString
|
|
DecodeString returns the bytes represented by the hexadecimal string s.
DecodeString返回十六进制字符串s所代表的字节数。
DecodeString expects that src contains only hexadecimal characters and that src has even length. If the input is malformed, DecodeString returns the bytes decoded before the error.
DecodeString期望src只包含十六进制的字符,并且src具有偶数长度。如果输入是畸形的,DecodeString将返回错误之前的解码字节。
Example
|
|
func DecodedLen
|
|
DecodedLen returns the length of a decoding of x source bytes. Specifically, it returns x / 2.
DecodedLen返回x个源字节的解码长度。具体来说,它返回x/2。
func Dump
|
|
Dump returns a string that contains a hex dump of the given data. The format of the hex dump matches the output of hexdump -C on the command line.
Dump返回一个包含给定数据的十六进制转储的字符串。十六进制转储的格式与命令行中hexdump -C的输出相匹配。
Example
|
|
func Dumper
|
|
Dumper returns a WriteCloser that writes a hex dump of all written data to w. The format of the dump matches the output of hexdump -C on the command line.
Dumper返回一个WriteCloser,将所有写入的数据的十六进制转储到w。
Example
|
|
func Encode
|
|
Encode encodes src into EncodedLen(len(src)) bytes of dst. As a convenience, it returns the number of bytes written to dst, but this value is always EncodedLen(len(src)). Encode implements hexadecimal encoding.
Encode将src编码为dst的EncodedLen(len(src))字节。为了方便起见,它返回写入dst的字节数,但这个值总是EncodedLen(len(src))。Encode实现了十六进制的编码。
Example
|
|
func EncodeToString
|
|
EncodeToString returns the hexadecimal encoding of src.
EncodeToString返回src的十六进制编码。
Example
|
|
func EncodedLen
|
|
EncodedLen returns the length of an encoding of n source bytes. Specifically, it returns n * 2.
EncodedLen返回n个源字节的编码的长度。具体来说,它返回n * 2。
func NewDecoder <- go1.10
|
|
NewDecoder returns an io.Reader that decodes hexadecimal characters from r. NewDecoder expects that r contain only an even number of hexadecimal characters.
NewDecoder返回一个io.Reader,对r中的十六进制字符进行解码。NewDecoder希望r中只包含偶数的十六进制字符。
func NewEncoder <- go1.10
|
|
NewEncoder returns an io.Writer that writes lowercase hexadecimal characters to w.
NewEncoder返回一个io.Writer,将小写的十六进制字符写入w中。
类型
type InvalidByteError
|
|
InvalidByteError values describe errors resulting from an invalid byte in a hex string.
InvalidByteError值描述由十六进制字符串中的无效字节导致的错误。
(InvalidByteError) Error
|
|
7.10 - json
json
https://pkg.go.dev/encoding/json@go1.20.1
json包实现了RFC 7159中定义的JSON编解码。JSON和Go值之间的映射在Marshal和Unmarshal函数的文档中有描述。
有关此包的介绍,请参见JSON和Go。
Example (CustomMarshalJSON)
|
|
Example(TextMarshalJSON)
|
|
常量
This section is empty.
变量
This section is empty.
函数
func Compact
|
|
Compact函数将JSON编码的src附加到dst中,省略了不重要的空格字符。
func HTMLEscape
|
|
HTMLEscape函数将JSON编码的src附加到dst中,将字符串文字内的<、>、&、U+2028和U+2029字符更改为\u003c、\u003e、\u0026、\u2028、\u2029,以使JSON可以安全地嵌入HTML <script>标记中。由于历史原因,Web浏览器不支持在<script>标记中使用标准的HTML转义,因此必须使用替代的JSON编码。
HTMLEscape Example
|
|
func Indent
|
|
Indent函数将JSON编码的src的缩进形式附加到dst中。JSON对象或数组中的每个元素都在新的缩进行上开始,该行以prefix开头,后跟一个或多个indent的副本,具体取决于缩进嵌套。附加到dst的数据不以prefix或任何缩进开始,以使其更容易嵌入其他格式化的JSON数据中。虽然src开头的前导空格字符(空格、制表符、回车、换行符)会被删除,但src末尾的尾随空格字符会被保留并复制到dst中。例如,如果src没有尾随空格,则dst也没有;如果src以尾随换行符结束,则dst也是如此。
Example
|
|
func Marshal
|
|
Marshal函数返回v的JSON编码。
Marshal函数递归遍历值v。如果遇到的值实现了Marshaler接口并且不是nil指针,则Marshal调用其MarshalJSON方法以生成JSON。如果没有MarshalJSON方法但该值代替实现了encoding.TextMarshaler,则Marshal调用其MarshalText方法并将结果编码为JSON字符串。nil指针异常并不是严格必要的,但模仿了在UnmarshalJSON的行为中必要的类似异常。
否则,Marshal使用以下类型相关的默认编码:
布尔值被编码为JSON布尔值。
浮点数、整数和Number类型的值被编码为JSON数字。
字符串类型的值被编码为JSON字符串,被强制转换为有效的UTF-8编码,无效的字节会被替换为Unicode替换符。为了将JSON安全地嵌入到HTML的